【问题标题】:How to access an instance variable of a derived class from a base class in Python如何从 Python 中的基类访问派生类的实例变量
【发布时间】:2019-05-05 10:32:15
【问题描述】:

我在 Python 中有下一个代码:

class Base_class():
    def __init__(self):
        pass

    # this is the method where I need help
    def compress(variable?,index?):
        somecode()

class Derived_class_1():   
    def __init__(self,somelist):
        self.A = []
        self.B = []
        for item in somelist:
            if item == 1:
                self.A.append([1,0])
                self.B.append([0,1])
            else:
                self.A.append([1,0])
                self.B.append([1,0])

class Derived_class_2(): 
    def __init__(self,somelist):
        self.A = []
        self.B = []
        for item in somelist:
            if item == 1:
                self.A.append([1,0])
                self.B.append([1,0])
            else:
                self.A.append([1,0])
                self.B.append([0,1])

我需要能够在基类的 compress 方法中访问每个实例值并根据索引返回一维列表,因为实例变量对于列表中的每个元素都有两个可能的值。我需要将压缩方法设为一类吗?如果是这样,我怎样才能使它成为可能?

【问题讨论】:

标签: python class inheritance instance derived-class


【解决方案1】:

我看到你的代码有 2 个问题。

  • Derrived 类不继承自 Base_class
  • compress 中缺少 self

变化:

class Base_class():
    # ...
    def compress(self, variable, index):
        print(self.A)
        print(self.B)

class Derived_class_1(Base_class):
    # ...

class Derived_class_2(Base_class):
    # ...

然后去测试

>>> x = Derived_class_1([1, 2])
>>> x.compress(5, 6)
[[1, 0], [1, 0]]
[[0, 1], [1, 0]]

>>> y = Derived_class_2([1, 2])
>>> y.compress(5, 6)
[[1, 0], [1, 0]]
[[1, 0], [0, 1]]

【讨论】:

    猜你喜欢
    • 2011-07-14
    • 2018-11-03
    • 1970-01-01
    • 2023-03-15
    • 2022-08-11
    • 1970-01-01
    • 2018-03-21
    • 2014-08-21
    • 1970-01-01
    相关资源
    最近更新 更多