1

Why do i get an "AttributeError: 'NewOne' object has no attribute 'self.b'" error message when i try to access the attribute 'self.b' from the NewOne class. I mean it's right there.

class NewOne(object):  
    def __init__(self):
        self.b = 'Cat' # this is what i want to access
    def child(self):
        self.c = 'kitten'
        return self.c

class FatherClass(object):
    def __init__(self, a):
        self.a = a
    def son(self):
        self.i = 'I and my father'
        return self.i
    def father(self):
        self.x = 'are one'
        return self.x
    def father_son(self):
        u = NewOne()
        k = getattr(u, 'self.b') #why does it tell me NewOne has no self.b attr
        return self.a, k()

Isn't getattr used to access a method? Why is it called getattr and not getmeth or something? Thanks

2 Answers 2

6

replace this:

k = getattr(u, 'self.b')

by this:

k = getattr(u, 'b')

or even better just do:

k = u.b
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you, thank you, thank you! what happens if an attribute and a method have the same name?
An attribute and a method cannot have the same name. More precisely, a method is an attribute, just one that is callable.
you're very welcome, it get overwrite by the last one that get defined, try it and see :)
2

Youe should write

k = getattr(u, 'b')

or better

k = u.b

instead.

The name of the attribute is b, not self.b. And usually you access attributes via obj.attr -- the getattr() form is only needed if the name of the attribute is dynamic (i.e. not known at the time you write the code, but computed at run time).

1 Comment

"the getattr() form is only needed if the name of the attribute is dynamic" That's illuminating. Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.