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

问题描述 投票:2回答:2

我非常喜欢Do Do Repeat Yourself(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

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

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

python python-2.7 inheritance dry
2个回答
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来避免任何其他类名。


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

© www.soinside.com 2019 - 2024. All rights reserved.