【发布时间】:2017-10-30 08:43:40
【问题描述】:
我正在尝试在父类中创建一个函数,该函数引用最终调用它的子类,以获取子类中的静态变量。
这是我的代码。
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 可以引用。
【问题讨论】:
-
实例方法的第一个参数应该是
self -
如果是静态的,应该有
staticmethod装饰器 -
函数是静态的,不需要
self。 -
你想如何从静态方法中获取类字段
attributes?它应该是类方法(用classmethod装饰)然后 -
我以前从未使用过
staticmethod装饰器。让我看看。
标签: python class parent-child static-variables static-classes