在Python中如何通过变量访问类属性?
在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
class TestClass(object)
pass
tc = TestClass()
setattr(tc, "foo", "bar")
print tc.foo
当然可以!请把你想要翻译的内容发给我,我会帮你用简单易懂的语言解释清楚。