在Python中如何通过变量访问类属性?

1 投票
2 回答
1048 浏览
提问于 2025-04-15 16:55

在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

当然可以!请把你想要翻译的内容发给我,我会帮你用简单易懂的语言解释清楚。

3

这个问题已经被问过很多次了。你可以使用 getattr 来通过名字获取一个属性:

print getattr(tc, 'foo')

这个方法同样适用于获取方法:

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

如果你想通过名字设置一个属性,可以使用 setattr

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

要检查一个属性是否存在,可以使用 hasattr

hasattr(tc, 'foo')

撰写回答