Reputation: 469
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
Upvotes: 1
Views: 461
Reputation: 70059
replace this:
k = getattr(u, 'self.b')
by this:
k = getattr(u, 'b')
or even better just do:
k = u.b
Upvotes: 6
Reputation: 602635
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).
Upvotes: 2