2009-12-11 122 views
1

在PHP我可以訪問類的屬性是這樣的:通過在Python中使用變量來訪問類屬性?

<?php // very simple :) 
class TestClass {} 
$tc = new TestClass{}; 
$attribute = 'foo'; 
$tc->{$attribute} = 'bar'; 
echo $tc->foo 
// should echo 'bar' 

我怎樣才能做到這一點在Python?

class TestClass() 
tc = TestClass 
attribute = 'foo' 
# here comes the magic? 
print tc.foo 
# should echo 'bar' 

回答

3

此問題已被多次詢問。您可以使用getattr按名稱獲取屬性:

print getattr(tc, 'foo') 

這適用於方法,以及:

getattr(tc, 'methodname')(arg1, arg2) 

要通過名稱使用的屬性集,setattr

setattr(tc, 'foo', 'bar') 

要檢查屬性存在使用hasattr

hasattr(tc, 'foo') 
+1

getattr的另一個有用的細節:它需要第三個(可選)參數,如果找不到屬性,它將提供默認值。如果未提供此參數,則如果未找到該屬性(AttributeError),則會引發異常。 – 2009-12-11 13:44:26

0
class TestClass(object) 
    pass 

tc = TestClass() 
setattr(tc, "foo", "bar") 
print tc.foo 
相關問題