[英]how to use variable of parent class
I want to access variable inside a method of parent class my code looks like this我想在父 class 的方法中访问变量我的代码如下所示
class func1:
def show(self):
self.data = 123
self.next = 100
def new(self):
self.num = self.data + self.next
print(self.num)
class func2(func1):
def new_num(self):
self.new = self.num * 3
print(super.num)
but this gives attribute error但这会产生属性错误
AttributeError: 'func2' object has no attribute 'num' AttributeError: 'func2' object 没有属性 'num'
Variables don't appear in an instance object until something assigns them values.变量不会出现在实例 object 中,直到某些东西为其赋值。 In your case, code that wants to call
new_num
must first call show
and new
to set self.num
.在您的情况下,想要调用
new_num
的代码必须首先调用show
和new
来设置self.num
。
class func1:
def show(self):
self.data = 123
self.next = 100
def new(self):
self.num = self.data + self.next
print(self.num)
class func2(func1):
def new_num(self):
self.new = self.num * 3
#print(super.num) # todo: I think this was just debug code...?
foo = func2()
foo.show()
foo.new()
foo.new_num()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.