user3150635
user3150635

Reputation: 547

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, )

Upvotes: 0

Views: 60

Answers (2)

Anshul Goyal
Anshul Goyal

Reputation: 76827

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

Upvotes: 3

aaazalea
aaazalea

Reputation: 7910

class entity:
    def __init__(self,person):
        self.entity = self
        self.person = person
        plant = True #you're not editting the object, this is a local variable

In order to edit an instance variable of your entity, you need to use self.

Upvotes: 1

Related Questions