Python 2.7访问超类属性不是DRY?

时间:2016-10-22 11:37:09

标签: python python-2.7 inheritance dry

我非常喜欢不要重复自己(DRY)的原则,作为其中的一个例子,我不想在其定义中使用类的名称。 (如果我想更改类名,我还必须在类定义中更改它的所有实例,我可能会在其中忘记一个。)

现在访问文档中读取的超类属性的典型习惯用法包含类名,如

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

使用"输入(自我)"或者" self .__ class __"相反,当子类化B.

时将导致无限递归

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

2 个答案:

答案 0 :(得分:1)

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来避免任何其他类名。

答案 1 :(得分:0)

我知道这是一个老问题,但我想把它留在这里作为参考。

可以使用metaclasses自动添加包含该类的属性。

这样的事情会起作用:

class Metaclass(type):
  def __init__(cls, name, bases, attrs):
    cls.what_class = cls

class A(metaclass=Metaclass):
  pass

class B(A):
  pass

print(A().what_class) # <class 'A'>
print(B().what_class) # <class 'B'>

如果你想将它与另一个元类一起使用,我会调查this question

相关问题