[英]How to access in base class method a certain class attributes all derived classes?
[英]Accessing class attributes in base (parent) class method with possible overloading by derived (children) 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
可以引用。
用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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.