Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python中使用变量访问类属性?_Python_Attributes - Fatal编程技术网

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

在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中,我可以访问如下类属性:

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