值不从Python中的子方法传播到父方法
以下是我的课程:值不从Python中的子方法传播到父方法,python,python-3.x,oop,inheritance,Python,Python 3.x,Oop,Inheritance,以下是我的课程: class A(Something): def __init__(self, **kwargs): super().__init__(**kwargs) self.amounts = [] self.counts = [] def common_method(self): amounts = self.amounts counts = self.counts
class A(Something):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.amounts = []
self.counts = []
def common_method(self):
amounts = self.amounts
counts = self.counts
print(amounts)
class B(A):
def construct(self):
counts = self.counts
amounts = [1, 2, 3, 4]
self.common_method()
当类B
被实例化时,这将导致打印[]
,而不是[1,2,3,4]
如果我从A
中删除amounts=self.amounts
,我会得到错误amounts
未定义。当从父类a
调用方法common\u method
时,如何获取B
中设置的金额值以保持不变
谢谢。在方法
B.construct
中,count
和amounts
是本地函数变量,在函数的单个调用之外,任何东西都不可见<代码>常用方法看不到它们。您要么需要参数化common\u方法
来获取这些值,要么考虑到common\u方法
使用对象的实例变量,让构造
填充它们
class A:
def __init__(self):
self.amounts = []
self.counts = []
def common_method(self):
amounts = self.amounts
counts = self.counts
print(amounts)
class B(A):
def construct(self):
self.amounts = [1, 2, 3, 4]
self.common_method()
B().construct()
在方法
B.construct
中,count
和amounts
是局部函数变量,在函数的单个调用之外,任何对象都不可见<代码>常用方法看不到它们。您要么需要参数化common\u方法
来获取这些值,要么考虑到common\u方法
使用对象的实例变量,让构造
填充它们
class A:
def __init__(self):
self.amounts = []
self.counts = []
def common_method(self):
amounts = self.amounts
counts = self.counts
print(amounts)
class B(A):
def construct(self):
self.amounts = [1, 2, 3, 4]
self.common_method()
B().construct()
self.common\u方法construct()
中缺少()
amounts=[1,2,3,4]
应该是self.amounts=[1,2,3,4]
同样,B
也不一定需要自己的\uuu init\uuu()
。我的意思是你似乎也打算发布:B=B();b、 construct()
。我们不能自己运行它,因为我们没有Something
类。它对问题不重要,因此可以删除它(并且在a
中根本不需要\uuuuu init\uuuu
)。目标是一个示例,我们可以在删除不需要的代码的情况下运行。construct()
中的self.common\u方法
应该是self.amounts=[1,2,3,4]
而且,B
不一定需要它自己的\u init
。我的意思是,似乎你也打算发布:b=b();b、 construct()
。我们不能自己运行它,因为我们没有Something
类。它对问题不重要,因此可以删除它(并且在a
中根本不需要\uuuuu init\uuuu
)。目标是一个示例,我们可以在删除不需要的代码的情况下运行。