2017-05-30 11 views
0

子クラスにある静的変数を取得するために子クラスが呼び出される親クラスの関数を作成しようとしています。Python:子クラスの静的変数を呼び出す

ここに私のコードです。

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

+0

インスタンスメソッドは、彼らが静的であれば、HTTPS([ 'staticmethod']がなければならない最初の引数 –

+0

として' self'を持っている必要があり、私たちを与えます://docs.python.org/2/library/functions.html#staticmethod)decorator –

+0

この関数は静的で、 'self'は必要ありません。 – MakPo

答えて

2

decorating

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 
+0

'@ classmethod'が動作するようになりました。ありがとうございました。 – MakPo

+0

@MakPo:あなたは[回答を受け入れる](https://stackoverflow.com/help/someone-answers)か、それを改善する方法を教えてください –

関連する問題