繁体   English   中英

是否可以从子类的方法中更改超类变量并在另一个子类中使用它?

[英]Is it possible to change the superclass variable from a subclass's method and use it in another subclass?

编辑: Dou 对@Prune 评论我已编辑问题

我有一个主要的 class 作为超类,并从它扩展了许多类。

我想从子类内部的方法更改超类的变量并在另一个子类中使用它。

假设:

class MainClass:
    def __init__(self):
        self.test = 'GOOGLE'   # This is a variable

    def plus(x, y):
        return x + y


class SubClassOne(MainClass):
    def __init__(self):
        super().__init__()


    def substract(self, x, y):
        return x + y
        self.test = 'YAHOO'    # Here I'm trying to change the 'test'


class SubClassTwo(MainClass):
    def __init__(self):
        super().__init__()

    def multiply(self, x, y):
        print(self.test)      # Here I'm printing the 'test' and I want to have it with 'YAHOO' value
        return x * y


run = SubClassTwo()
run.multiply(2,5)

1- 在 SuperClass 初始化中查看变量self.test = 'GOOGLE'

2-然后我在SubClassOne.substract()中将其更改为self.test = 'YAHOO'

3- 我在 SubClassTwo 中使用self.test来实现来自 SubClassOne 的更改。

意味着如果我打印它,我想要 output 中的YAHOO 但实际的 output 是GOOGLE

我应该怎么办?

您的设计假设存在严重缺陷:

3- 我在 SubClassTwo 中使用 self.test 来实现来自 SubClassOne 的更改。

不,你没有。 SubClassTwo 和 SubClassOne 是同级子类。 SubClassTwo 中的self.test指的是 SubClassTwo 实例的test属性; SubClassOne 不是这个谱系的任何部分。 SubClassTwo仅从MainClass 继承。 对 SubClassOne 实例的test属性的更改不会自动影响 SubClassTwo 实例。

在您对旧答案的评论中,我看到您的问题可能是什么:

运行时的方法是按顺序连续的,ClassOne 然后 Class 两个

您声明了两个相互独立的子而不是方法。 substract() [原文如此] 和multiply是两个不同类的方法。 例如,您是否在发布代码的末尾尝试,

print(run.substract(5, 2))

你会得到一个run时错误: run没有名为substract的方法——run 的类型是 SubClassTwo,它没有这样的方法。 substract只是 SubClassOne 的一种方法。


很简单,你需要确定你想让你的对象做什么,然后编写相应的Python结构来匹配。 由于您没有告诉我们有关您想要的操作的足够信息,我们无法更改您发布的代码以匹配。 简单地设置一个实例属性只需要一个 class,而不是三个。

You cant get YAHOO as output by self.test of the second class, attributes and methods of classes works in that way: B inherits from A, when you create an object, and you try to execute a method or class of that object, it将首先在 class A 中搜索,然后是 B,所以如果它没有在 B 中重新声明,它将显示 A 的那个,这就是你的情况,属性self.test没有在SubClassTwo中重新声明,所以这是正常的它会将GOOGLE显示为output,您还必须在该子class上重新定义它

您可以使SubClassTwoSubClassOne继承,因为它还将继承该覆盖行为:

class SubClassTwo(SubClassOne):
    def multiply(self, x, y):
        print(self.test)  # prints "YAHOO"
        return x * y

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM