通过在Python中使用变量来访问类属性?

时间:2009-12-11 11:39:26

标签: python attributes

在PHP中,我可以访问类属性:

<?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'

2 个答案:

答案 0 :(得分:3)

这个问题已被问过好几次了。您可以使用getattr按名称获取属性:

print getattr(tc, 'foo')

这也适用于方法:

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

要按名称设置属性,请使用setattr

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

要检查属性是否存在,请使用hasattr

hasattr(tc, 'foo')

答案 1 :(得分:0)

class TestClass(object)
    pass

tc = TestClass()
setattr(tc, "foo", "bar")
print tc.foo