首页 > python > 我应该把一个参数作为继承对象吗?

我应该把一个参数作为继承对象吗? (Should I take an argument as an inheritance object?)

问题

所以我遇到了一个我一直在考虑的想法。我对此很怀疑,但它确实有效,所以我想知道是否有人有这样的经历:

def make_new_class(Koola,Booba):

    class Bar(Koola,Booba):
        def __init__(self):
            Koola.__init__(self)
            Booba.__init__(self)

    return Bar

Koola和Booba是其他课程。

所以这确实有效。但是很少有人谈论这种可能性。

这是好习惯吗?如果不是什么选择?

如果你对这可能出现的地方感到好奇; 在您希望从各种子类继承的类的情况下,可能会出现这种情况。也许你有一堆算法以不同的方式做同样的事情,你想把它们像legos一样粘在一起。

解决方法

谢谢你的问题!

类是python中的一等公民,因此使用它们进行任何操作都与使用任何其他对象进行操作一样好。但是多重继承是非常讨厌的事情,如果可能的话应该完全避免。

请注意这一点:

class A1:
    def __init__(self):
        self.a = 1

class A2:
    def __init__(self):
        self.a = 2

Composed1 = compose(A1, A2)
c1 = Composed1()
print(c1.a)   # prints 2

Composed2 = compose(A2, A1)
c2 = Composed2()
print(c2.a)   # prints 1

这是最明显的警告。还有很多其他的。

你应该受到警告。

问题

So I came across an idea that I have been mulling about. I'm suspicious about it but it works so I was wondering if anyone has any experience working with something like this:

def make_new_class(Koola,Booba):

    class Bar(Koola,Booba):
        def __init__(self):
            Koola.__init__(self)
            Booba.__init__(self)

    return Bar

Where Koola and Booba are other classes.

So this actually works. But have found very little talking about this possibility.

Is it good practice? If not what are the alternatives?

If you are curious of where this might turn up; This might come up in situations where you want a class that inherits from a variety of subclasses. Maybe you have a bunch of algorithms that do the same thing in different ways and you want to stick them together like legos.

解决方法

Thank you for your question!

Classes are first-class citizen in python, so any manipulation with them is as good as manipulation with any other object. But multiple inheritance is quite nasty thing and should be avoided at all, if possible.

Be aware of this:

class A1:
    def __init__(self):
        self.a = 1

class A2:
    def __init__(self):
        self.a = 2

Composed1 = compose(A1, A2)
c1 = Composed1()
print(c1.a)   # prints 2

Composed2 = compose(A2, A1)
c2 = Composed2()
print(c2.a)   # prints 1

And this is the most obvious caveat. There are many others.

Ye be warned.

相似信息