2017-03-13 10 views
0

どの引数が渡されたかによって決まる属性を呼び出す関数を作成しようとしています。引数を使用してオブジェクトの属性を参照する

class room: 
    def __init__(self, length, bredth, depth): 
     self.length = length 
     self.bredth = bredth 
     self.depth = depth 

    def displaymeasurement(self, side): 
     print(self.side) 


kitchen = room(10, 20, 15) 

room.displaymeasurement("depth") 

これは私が使用しているコードの抽象化であり、複雑すぎます。問題のコードに一致させるよう努力しましたが、同じエラーメッセージが生成されます。

Traceback (most recent call last): 
    File "/home/townsend/Documents/PycharmProjects/untitled2/Test/inplicitreference.py", line 13, in <module> 
    room.displaymeasurement("depth") 
    File "/home/townsend/Documents/PycharmProjects/untitled2/Test/inplicitreference.py", line 8, in displaymeasurement 
    print(self.side) 
AttributeError: 'shape' object has no attribute 'side' 

何構文私はそこから入力された引数depthとプロセスとsideを置き換えるために、コンピュータと通信するために不足しています。

私は2,3日間の検索に過ごしましたが、同様の構成では試してみることができません。おそらく、私は誤った用語を使用しているからでしょう。私はこれに非常に新しいです。

私はこの方法がうまくいくとは思っていませんが、説明するのが最善の方法だと思いました。私はいくつかの異なる方法を試しました。

私は解決策として一連のifチェックを知っていますが、私はよりシンプルで拡張性の高いソリューションがあると確信しています。

+0

あなたは 'getattr'たい:' 'プリント(GETATTR(自己、側)) – mgilson

答えて

0

教室: DEF INIT(自己、長さ、bredth、深さ): self.length =長 self.bredth = bredth self.depth =奥行き

def displaymeasurement(self, side): 
    print(getattr(self, side)) 

キッチン=部屋(10、20、15)

room.displaymeasurement( "深さ")

0

これは、オブジェクトのルックアップテーブル内のメンバーを検索する脆弱な方法です。 getattr()は、このユースケースのみを対象としています。実施例以下:

class MyClass(object): 
    def __init__(self): 
     self.x = 'foo' 
     self.y = 'bar' 

myClass = MyClass() 

try: 
    print(getattr(myClass, 'x')) 
    print(getattr(myClass, 'y')) 
    print(getattr(myClass, 'z')) 

except AttributeError: 
    print 'Attribute not found.' 

出力例:

foo 
bar 
Attribute not found. 
関連する問題