我怎样才能获得父类?自己?
class Test1:
def __init__(self):
self.x = 1
class Test2(Test1):
# how can I get parent class's self.x ??
# exactly here not def __init__(self) or other methods in Test2..
拜托...我花了几个小时弄清楚如何获得父类的自我!并失败了.. 我需要一个Python专家!
class Test1:
def __init__(self):
self.x = 1
class Test2(Test1):
# how can I get parent class's self.x ??
# exactly here not def __init__(self) or other methods in Test2..
Please... I spent hours figuring out how to get parent class' self! and failed..
I need a python expert!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你想要这样的东西吗?
您可以在 Test2 中访问 self.x,因为 Test2 对象具有 x 属性。它是在 Test1 初始化程序中创建的。
编辑:在作者解释了我的误解之后,不可能执行所要求的操作,因为 x 是实例成员,而不是类成员。请参阅 gecco 的回答。
Do you want something like this?
You can access self.x inside Test2, because the Test2 object has the x attribute. It is created in Test1 initializer.
Edit: After the author explaining my misunderstanding, it is not possible to do what is asked, because x is an instance member, and not a class one. See gecco's answer.
这是不可能的。 self.x 是一个实例变量。实例变量只能从实例方法内访问。在方法之外,您处于静态上下文中。
你可以这样做(纯类变量(不是实例)):
This is not possible.
self.x
is an instance variable. Instance variables can only be accessed from within instance-methods. Outside methods you are in a static context.You can do this (pure class-variables (not instance)):
在类定义时,不存在对象,因此不存在
self
-self
仅在成员函数内有意义。无论如何,您想要类定义中的self.x
做什么?At the point of class-definition there is no object, so there is no
self
-self
only has a meaning inside member-functions. What do you want withself.x
in the class-definition anyway?