如何使用子类修改父类变量并在python中的另一个子类中使用

qua*_*uas 1 python oop inheritance

class A(object):
    __A = None
    def get_a(self):
        return self.__A
    def set_a(self, value):
        self.__A = value

class B(A):
    def method_b(self, value):
        self.set_a(value)

class C(A):
    def method_c(self)
         self.get_a()
Run Code Online (Sandbox Code Playgroud)

有人可以解释我如何捕获“C”类方法中 method_b 中的安装值?

PS 在这个变体中我什么也没得到。

PM *_*ing 5

Python 不是 Java;这里不需要 setter 和 getter:只需直接访问属性即可。

您的代码存在三个问题。

  1. C.method_c()没有return声明,因此返回None

  2. 当您想要的时候,您正在使用__ 名称修改

  3. 您想要A.set_a()设置一个类属性,但您的赋值却创建了一个隐藏该类属性的实例属性。

这是修复后的版本。

class A(object):
    _A = 'nothing'
    def get_a(self):
        return self._A
    def set_a(self, value):
        A._A = value

class B(A):
    def method_b(self, value):
        self.set_a(value)

class C(A):
    def method_c(self):
        return self.get_a()

b = B()
c = C()
print(c.method_c())
b.method_b(13)
print(c.method_c())
Run Code Online (Sandbox Code Playgroud)

输出

nothing
13
Run Code Online (Sandbox Code Playgroud)

这是一个稍微Pythonic 的版本:

class A(object):
    _A = 'nothing'

class B(A):
    def method_b(self, value):
        A._A = value

class C(A):
    pass

b = B()
c = C()
print(c._A)
b.method_b(13)
print(c._A)
Run Code Online (Sandbox Code Playgroud)