理解Python类初始化

时间:2011-06-03 16:26:11

标签: python superclass

假设我有两个类:

class A():
    pass

class B():
    pass

我有另一个班级

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

如果我从A或B继承,可以通过这种实现吗?

4 个答案:

答案 0 :(得分:4)

如果要设置类,请使用__class__变量。

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

答案 1 :(得分:3)

既然你没有给出一个非常好的例子,为什么那可能有用,我只是假设你不理解OOP。

您尝试做的可能是某种工厂模式:

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

myobj = something_useful(cond)

或者你想要聚合:

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())

答案 2 :(得分:1)

你的意思是你想根据cond的价值进行某种混合吗?

若是,请尝试

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

我不是100%确定这是可能的,因为它可能只有C. 基础 + = A.如果不可能那么你想要做的事情可能是不可能的。 C应该从A继承或从B继承。

答案 3 :(得分:1)

虽然我不会像Jochen那样严厉,但我会说你可能采取了错误的做法。即使有可能,使用multiple inheritance并拥有AC和BC类也会好得多。

例如:

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

这样,您只需致电

即可
def get_a_c(cond):
    if cond == True:
       return AC()
    return BC()
相关问题