在Python中使用变量访问类属性?
在PHP中,我可以访问如下类属性:在Python中使用变量访问类属性?,python,attributes,Python,Attributes,在PHP中,我可以访问如下类属性: <?php // very simple :) class TestClass {} $tc = new TestClass{}; $attribute = 'foo'; $tc->{$attribute} = 'bar'; echo $tc->foo // should echo 'bar' 这个问题已经被问了好几次了。可以使用按名称获取属性: print getattr(tc, 'foo') 这也适用于以下方法: getattr(tc
<?php // very simple :)
class TestClass {}
$tc = new TestClass{};
$attribute = 'foo';
$tc->{$attribute} = 'bar';
echo $tc->foo
// should echo 'bar'
这个问题已经被问了好几次了。可以使用按名称获取属性:
print getattr(tc, 'foo')
这也适用于以下方法:
getattr(tc, 'methodname')(arg1, arg2)
要按名称设置属性,请使用
要检查属性是否存在,请使用
关于getattr的另一个有用细节:它使用第三个(可选)参数,如果找不到该属性,该参数将提供默认值。如果未提供此参数,则如果未找到该属性(AttributeError),将引发异常。
getattr(tc, 'methodname')(arg1, arg2)
setattr(tc, 'foo', 'bar')
hasattr(tc, 'foo')
class TestClass(object)
pass
tc = TestClass()
setattr(tc, "foo", "bar")
print tc.foo