开发者

Understanding Python Class Initialization

Suppose I have two classes:

class A():
    pass

class B():
    pass

I have another 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 impleme开发者_如何转开发ntation is it possible?


If you want to set the class use the __class__ variable.

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.

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?

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.bases += A. If it's not possible then what you are trying to do is probably not possible. C should either inherit from A or from B.


While I'll not be as severe as Jochen, I will say that you are likely taking the wrong approach. Even if it is possible, you're far better off using multiple inheritance and having an AC and a 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()
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜