Search code examples
pythonoopgetattr

why won't getattr work for built in attributes?


The following code should print "person is true" and "plant is true", but it only prints the first one. I've tested it, and for some reason my code only works for attributes that are set after the fact, not ones that are always true or false in the constructor. What am I doing wrong?

class entity:
    def __init__(self,person):
        self.entity = self
        self.person = person
        plant = True

e = entity(True)
for attribute in dir(e):
    if getattr(e, attribute) is True:
        print '"%s" is True' % (attribute, )

Solution

  • You have written plant = True in the __init__ method which makes it a local variable and not an attribute.

    Change it to:

    def __init__(self,person):
        self.entity = self
        self.person = person
        self.plant = True