要在類中創建屬性,只需執行self.property = value
。我希望能夠讓這個類中的屬性完全依賴於一個參數。讓我們稱這個類爲Foo
。在Foo
類的Python非常動態的類屬性
情況下將採取的元組的列表:
l = [("first","foo"),("second","bar"),("anything","you get the point")]
bar = Foo(l)
現在我們分配給bar
將具有以下屬性Foo
類的實例:
bar.first
#foo
bar.second
#bar
bar.anything
#you get the point
這是甚至遠程可能?怎麼樣?
看看['setattr'](http://docs.python.org/2/library/functions.html#setattr)。 – BrenBarn
您可能還想查看['namedtuple'](http://docs.python.org/2/library/collections.html#collections.namedtuple)。 –
setattr完美運作!謝謝。我會看看namedtuple –