1

In PHP I can access class attributes like this:

<?php // very simple :)
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'
vaultah
  • 44,105
  • 12
  • 114
  • 143
DerKlops
  • 1,249
  • 1
  • 12
  • 24

2 Answers2

3

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')
Nadia Alramli
  • 111,714
  • 37
  • 173
  • 152
  • 1
    Another useful detail on getattr: it takes a third (optional) argument, which supplies the default value if the attribute is not found. If this argument is not supplied, then an exception is raised if the attribute is not found (AttributeError). – Edward Loper Dec 11 '09 at 13:44
0
class TestClass(object)
    pass

tc = TestClass()
setattr(tc, "foo", "bar")
print tc.foo
codeape
  • 97,830
  • 24
  • 159
  • 188