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
replace this:
k = getattr(u, 'self.b')
by this:
k = getattr(u, 'b')
or even better just do:
k = u.b
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 (ie not known at the time you write the code, but computed at run time).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.