python中3个类之间的继承
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python中3个类之间的继承相关的知识,希望对你有一定的参考价值。
我正在使用PyQt5创建一个创建wordclouds的程序。
该程序具有:1。获取文本并生成wordcloud的主窗口2.具有3种颜色选项的设置窗口
我需要将用户选择的颜色从设置窗口传递到主窗口。为此,我创建了3个类:
class A:
def __init__(self, colormap):
self.colormap = colormap
def set_colormap(self, x):
self.colormap = x
def get_colormap(self):
return self.colormap
#in the real program this class represents the second window with the color pick options:#
class B(A):
def __init__(self):
A.__init__(self, "blue")
self.c = A("blue")
def userColorChoice(self):
userinput = input("Choose ColorMap: \n")
#in the real program there are 3 button for options instead of this input#
c.set_colormap(userinput)
和:
from test2 import B
#in the real program this represnts the class of the main window which includes the create wordcloud function:#
class C(B):
def __init__(self):
Func = B()
self.ChosenColorMap = Func.c.get_colormap()
def create_wordcloud(self):
#here i'm using the self.ChosenColorMap#
我的问题是,当我在我的self.ChosenColorMap
中使用class C
时,它获得了self.c
的默认值(在这种情况下:“blue”)而不是用户选择。
我认为这个问题出现在Func = B()
的class C
中,因为无论何时我称之为self.c
都将其初始化为“蓝色”。
我该如何解决?
谢谢
您的代码中确实存在一些问题。让我们从你的C
课程开始吧。在这里,您创建一个名为Func的B类对象,并询问其颜色映射。 Func中的引用不存储在任何地方。因此,只要你的__init__(self)
类中的C
方法完成,Func中的引用就会丢失。您应该通过实际启动父类A类来启动您的C类,类似于启动B类的方式。您对self.c的分配很可能不是您想要的。
让我们看看你的类B.你启动父类,然后为self.c
分配一个新的A实例。这意味着self.c
不引用你继承的相同的A对象。
基于此,我要说你需要了解如何正确启动对象层次结构来解决这个问题。对于Python 3,您可以先了解https://www.python-course.eu/python3_inheritance.php。当Python 3看到光明之日时,如何改变这一点。 Python 2的表现不同,请参阅Python 2的https://www.python-course.eu/inheritance_example.php。其他网站当然也有不同程度的描述。
以上是关于python中3个类之间的继承的主要内容,如果未能解决你的问题,请参考以下文章
解决Python中abc.Sequence、abc.Hashable、list之间的继承矛盾