【问题标题】:Values not propagating to parents method from child in Python值不会从 Python 中的子级传播到父级方法
【发布时间】:2020-11-28 18:44:00
【问题描述】:

这是我的课程:

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_method 时,如何使B 中设置的金额值保持不变。

谢谢。

【问题讨论】:

  • construct() 中的self.common_method 缺少()。
  • amounts = [1, 2, 3, 4] 应该是 self.amounts = [1, 2, 3, 4]
  • 另外,B 不一定需要自己的__init__()。
  • 我的意思是,您似乎也打算发布:b = B(); b.construct()。
  • 我们不能自己运行它,因为我们没有 Something 类。这个问题并不重要,因此可以删除它(在A 中根本不需要__init__)。目标是一个我们可以在删除不需要的代码的情况下运行的示例。

标签: python python-3.x oop inheritance


【解决方案1】:

在方法B.construct、count 和amounts 中是局部函数变量,对函数的单次调用之外的任何内容均不可见。 common_method 没有看到它们。您要么需要参数化 common_method 以获取这些值,要么考虑到 common_method 使用对象的实例变量,让 construct 填充它们。

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()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-28
    • 1970-01-01
    • 2015-07-28
    • 1970-01-01
    • 2014-03-11
    相关资源
    最近更新 更多