访问基本(父)class 方法中的 class 属性,派生(子)classes 可能重载
Accessing class attributes in base (parent) class method with possible overloading by derived (children) classes
我正在尝试在父 class 中创建一个函数,该函数引用子 class 最终调用它以获得子 [=21= 中的静态变量].
这是我的代码。
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__
的 class 实例,我知道我会怎么做,但在这种情况下没有 self
可供参考。
decorating with 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
我正在尝试在父 class 中创建一个函数,该函数引用子 class 最终调用它以获得子 [=21= 中的静态变量].
这是我的代码。
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__
的 class 实例,我知道我会怎么做,但在这种情况下没有 self
可供参考。
decorating with 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