访问基(父)类方法中的类属性,可能由派生(子)类重载

时间:2017-05-30 02:50:48

标签: python class parent-child static-variables static-classes

我正在尝试在父类中创建一个函数,该类引用哪个子类最终调用它以获取子类中的静态变量。

这是我的代码。

class Element:
  attributes = []

  def attributes_to_string():
    # do some stuff
    return ' | '.join(__class__.attributes) # <== This is where I need to fix the code.

class Car(Element):
  attributes = ['door', 'window', 'engine']

class House(Element):
  attributes = ['door', 'window', 'lights', 'table']

class Computer(Element):
  attributes = ['screen', 'ram', 'video card', 'ssd']

print(Computer.attributes_to_string())

### screen | ram | video card | ssd

如果它是使用self.__class__的类的实例,我知道如何执行此操作,但在这种情况下没有self引用。

1 个答案:

答案 0 :(得分:3)

带有decorating

classmethod应该可以使用

class Element:
    attributes = []

    @classmethod
    def attributes_to_string(cls):
        # do some stuff
        return ' | '.join(cls.attributes)


class Car(Element):
    attributes = ['door', 'window', 'engine']


class House(Element):
    attributes = ['door', 'window', 'lights', 'table']


class Computer(Element):
    attributes = ['screen', 'ram', 'video card', 'ssd']


print(Computer.attributes_to_string())

给我们

screen | ram | video card | ssd