我正在尝试在父类中创建一个函数,该类引用哪个子类最终调用它以获取子类中的静态变量。
这是我的代码。
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
引用。
答案 0 :(得分:3)
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