简体   繁体   English

了解 Python Class 初始化

[英]Understanding Python Class Initialization

Suppose I have two classes:假设我有两个类:

class A():
    pass

class B():
    pass

I have another class我还有另一个 class

class C(object):
    def __init__(self, cond):
        if cond ==True:
           # class C initialize with class A
        else:
           # class C initialize with class B

If I inherit from A or B, by this implementation is it possible?如果我从 A 或 B 继承,通过这种实现是否可能?

If you want to set the class use the __class__ variable.如果要设置 class 使用__class__变量。

class C(object):
    def __init__(self, cond):
        if cond ==True:
           self.__class__ = A
        else:
           self.__class__ = B
        self.__class__.__init__(self)

Since you didn't give a very good example why that could ever be useful I'll just assume that you didn't understand OOP.由于您没有给出一个很好的例子,为什么这可能有用,我只是假设您不了解 OOP。

What you're trying to do might be some kind of factory pattern:您尝试做的可能是某种工厂模式:

def something_useful(cond):
    if cond:
        return A()
    else:
        return B()

myobj = something_useful(cond)

or maybe you want aggregation:或者你可能想要聚合:

class C(object):
    def __init__(self, something_useful):
        # store something_useful because you want to use it later
        self.something = something_useful

# let C use either A or B - then A and B really should inherit from a common base
if cond:
    myobj = C(A())
else:
    myobj = C(B())

Do you mean you want to do some sort of mix-in depending on the value of cond?您的意思是您想根据 cond 的值进行某种混合吗?

If so try如果是这样试试

class C(object):
    def __init(self, cond):
        if cond ==True:
           self.__bases__ += A
        else:
           self.__bases__ += B

I'm not 100% sure this is possible since perhaps it only works C.我不是 100% 确定这是可能的,因为它可能只适用于 C。 bases += A. If it's not possible then what you are trying to do is probably not possible. bases += A. 如果不可能,那么您尝试做的事情可能是不可能的。 C should either inherit from A or from B. C 应该从 A 或 B 继承。

While I'll not be as severe as Jochen, I will say that you are likely taking the wrong approach.虽然我不会像 Jochen 那样严厉,但我会说你可能采取了错误的方法。 Even if it is possible, you're far better off using multiple inheritance and having an AC and a BC class.即使有可能,您最好使用多个 inheritance并拥有一个 AC 和一个 BC class。

Eg:例如:

class A():
    pass

class B():
    pass

class C():
    #do something unique which makes this a C
    pass

#I believe that this works as is?
class AC(A,C):
    pass

class BC(B,C):
    pass

This way, you can simply call这样,您可以简单地调用

def get_a_c(cond):
    if cond == True:
       return AC()
    return BC()

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

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