简体   繁体   English

在 Python 中初始化基础 class 中的公共属性

[英]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.我有以下抽象类的情况 - 有一个基础 class A,比如说,继承类 B 和 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. B 和 C 有一些属性以自己的方式初始化,但是,有些属性对于所有继承的类应该具有相同的初始值。 Is there any way to initialize them in the base class without duplicating the code in each inherited class initialization?有没有办法在基础 class 中初始化它们,而无需在每个继承的 class 初始化中复制代码? 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.这是我第一次在 Python 中使用抽象类,在互联网上挖掘了几天后,我仍然找不到合适的解决方案。

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 的__init__方法中初始化值并在 B class 中调用super内置函数:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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