In PHP I can access class attributes like this:
class TestClass {}
$tc = new TestClass{};
$attribute = 'foo';
$tc->{$attribute} = 'bar';
echo $tc->foo
// should echo 'bar'
How can I do this in Python?
class TestClass()
tc = TestClass
attribute = 'foo'
# here comes the magic?
print tc.foo
# should echo 'bar'
解决方案
This question has been asked several times. You can use getattr to get the attribute by name:
print getattr(tc, 'foo')
This works for methods as well:
getattr(tc, 'methodname')(arg1, arg2)
To set an attribute by name use setattr
setattr(tc, 'foo', 'bar')
To check if an attribute exists use hasattr
hasattr(tc, 'foo')