Skip to main content
 首页 » 编程设计

Python 2.7 访问父类(super class)属性不是 DRY

2025年04月02日10shihaiming

我非常喜欢 Don't Repeat Yourself (DRY) 原则,作为它的一个实例,我不喜欢在其定义中使用类的名称。 (如果我想更改类名,我还必须更改它在类定义中的所有出现,我可能会忘记一个。)

现在我在文档中读到的访问父类(super class)属性的典型习语包含类名,如

class A(object): 
    def method(self): 
        print('Hi!') 
class B(A): 
    def method(self): 
        super(B, self).method()  # fixed reference to B, not DRY 

使用“type(self)”或“self.__class__”代替将在子类化 B 时导致无限递归。

在这种情况下我必须跳过 DRY 吗?或者是否有其他一些神奇的属性 - 在子类的定义中 - 指的是那个子类?

请您参考如下方法:

example in the documentation使用子类的显式名称。据我所知,这只是 Python 2.7 的一个不幸且不可避免的缺陷。

但是,这似乎对我有用:

class A(object): 
    def method(self): 
        print('Class A method') 
class B(A): 
    def __init__(self): 
        self.myclass = B 
        super(self.myclass, self).__init__() 
    def method(self): 
        print('Class B method') 
        super(self.myclass, self).method() 

这会在 B 中留下一次显式类名,但我可以通过使用 self.myclass 避免任何其他出现。