Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/292.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
值不从Python中的子方法传播到父方法_Python_Python 3.x_Oop_Inheritance - Fatal编程技术网

值不从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
)。目标是一个示例,我们可以在删除不需要的代码的情况下运行。