【问题标题】:Multiple inheretince in classes with functions that have the same name [duplicate]具有相同名称的函数的类中的多重继承[重复]
【发布时间】:2023-03-03 03:20:02
【问题描述】:

如果您有一个使用多重继承的类,并为一个函数使用两个同名的类,那么哪个函数优先?从我发现类声明中首先出现的函数优先。有没有比我现在拥有的更好的方法来调用第二个列出的类中的函数?

class test():
    number = 10
    def __init__(self, x, y, z):
        self.x = x
        self.y = y
        self.z = z
        self.something = z
    def printnumber(self):
        print(self.number)
class trial():
    def __init__(self,a,b,c):
        self.a = a
        self.b = b
        self.c = c
    def printnumber(self):
        print(self.c)
class check(test, trial):
    def __init__(self, a, b, c,x,y,z):
        trial.__init__(self ,a, b, c)
        test.__init__(self, x,y,z)
    def printnumber(self):
        return trial.printnumber(self)

另外,只是好奇,在多个继承或一般类中,您在类标题中列出类的顺序是否重要?

【问题讨论】:

  • 重命名函数之一?

标签: python class multiple-inheritance


【解决方案1】:

搜索顺序基本上是深度优先,从左到右。

https://docs.python.org/3/tutorial/classes.html

但是,由于它引起的混乱,编写这样的代码通常是不好的形式。多重继承(除了非常有用的混合概念之外)是一种危险的做法,从长远来看很少有回报。

【讨论】:

    猜你喜欢
    • 2020-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-02
    • 2013-03-03
    • 2012-03-04
    相关资源
    最近更新 更多