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

问题描述 投票:0回答:1

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

这是我的代码。

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可供参考。

python class parent-child static-variables static-classes
1个回答
3
投票

decoratingclassmethod应该工作

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
© www.soinside.com 2019 - 2024. All rights reserved.