简体   繁体   中英

Initializing common attributes in the base class in Python

I have the following case with abstract classes - there is a base class A and, say, inheriting classes B and C. B and C have some attributes initialized in their own way, however, there are some attributes that should have the initial value same for all the inherited classes. Is there any way to initialize them in the base class without duplicating the code in each inherited class initialization? It's my first time working with abstract classes in Python, and after digging the internet for couple of days I was still unable to find a proper solution.

Example:

class A(metaclass=ABCMeta):
    @abstract_attribute
    def name(self):
        pass

# Value should be set as 0 initially for all the classes
#Should it be written in the base __init__ somehow?
    @abstract_attribute
    def value(self):
        return 0

class B(A):
    def __init__(self):
        self.name = "class B"
        self.value = 0    # this is the duplicating line

class C(A):
    def __init__(self):
        self.name = "class C"
        self.value = 0    # this is the duplicating line

You can do it initializing the value in the __init__ method of class A and calling the super builtin in the B class:

class A():
    def __init__(self):
        self.value = 1
        
    def name(self):
        pass

class B(A):
    def __init__(self):
        super().__init__()
        self.name = "class B"

b = B()
print(b.value)

Print:

1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM