繁体   English   中英

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

[英]Initializing common attributes in the base class in Python

我有以下抽象类的情况 - 有一个基础 class A,比如说,继承类 B 和 C。 B 和 C 有一些属性以自己的方式初始化,但是,有些属性对于所有继承的类应该具有相同的初始值。 有没有办法在基础 class 中初始化它们,而无需在每个继承的 class 初始化中复制代码? 这是我第一次在 Python 中使用抽象类,在互联网上挖掘了几天后,我仍然找不到合适的解决方案。

例子:

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

您可以在 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)

打印:

1

暂无
暂无

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

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