[英]Is it possible to change the superclass variable from a subclass's method and use it in another subclass?
[英]Is it possible to access the variable from a method of a superclass in a subclass?
我有一个父类“父”,它有一个方法“method1”。 此方法使用我想从子类“Child”访问的变量“b”。 当我尝试将其作为self.b访问时,python抱怨“'Child'对象没有属性'b'”。 我是面向对象编程和python的新手。 所以也许我的理解是错误的。 请帮我解释为什么我无法访问'b'。
class Parent(object):
def __init__(self):
self.a = 1
def method1(self):
b = 2
class Child(Parent):
def __init__(self):
super(Child,self).__init__()
self.vara = self.a
self.varb = self.b
x = Child()
print x.vara
print x.varb
我加上了“自我”。 变量“b”的限定符,并在Parent类的init函数中添加相同的内容,认为它将使子类可见。
class Parent(object):
def __init__(self):
self.a = 1
self.b = 1
def method1(self):
self.b = 2
class Child(Parent):
def __init__(self):
super(Child,self).__init__()
self.vara = self.a
self.varb = self.b
x = Child()
print x.vara
print x.varb
我原以为输出会是
1
2
因为我认为method1下的self.b会覆盖init函数中的self.b. 但是,输出是
1
1
问题是你永远不会在任何地方调用method1
,所以self.b
永远不会被设置为值2
。
你可以只删除整个method1
,并有Parent
类是这样的:
class Parent(object):
def __init__(self):
self.a = 1
self.b = 2
要么
您可以在Child
类中调用method1
,例如:
class Child(Parent):
def __init__(self):
super(Child, self).__init__()
self.method1()
self.vara = self.a
self.varb = self.b
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.