简体   繁体   English

python OOP,访问属性

[英]python OOP, accessing attributes

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. 当我尝试从NewOne类访问属性'self.b'时,为什么会出现“ AttributeError:'NewOne'对象没有属性'self.b'”的错误消息。 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? getattr不用于访问方法吗? Why is it called getattr and not getmeth or something? 为什么叫getattr而不叫getmeth之类? 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 . 该属性的名称是b ,而不是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). 通常,您可以通过obj.attr访问属性-仅当属性名称是动态的(即在编写代码时未知,但在运行时计算getattr()时才需要getattr()形式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM