gpt4 book ai didi

python - 在Python中使用变量访问类属性?

转载 作者:行者123 更新时间:2023-12-01 00:00:07 24 4
gpt4 key购买 nike

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

最佳答案

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

print getattr(tc, 'foo')

这也适用于方法:

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

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

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

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

hasattr(tc, 'foo')

关于python - 在Python中使用变量访问类属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1887509/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com