簡體   English   中英

在基類(父類)方法中訪問類屬性,派生的(子類)類可能會重載

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM