Wednesday, 15 January 2014

python - Decide baseclass at runtime -



python - Decide baseclass at runtime -

i want this:

class a: def methoda(self): homecoming 5 class b: def methodb(self): homecoming 10 class x(...): def __init__(self, baseclass): if baseclass =='a' : derive x elif baseclass == 'b' : derive x b else: raise exception("not supported baseclass %s!" % (baseclass)) def methodx(self): homecoming 42 x('a').methoda() # returns 5 x('a').methodx() # returns 42 x('a').methodb() # methodb not defined x('b').methodb() # returns 10 x('b').methodx() # returns 42 x('a').methoda() # methoda not defined

how can implement this?

if want add together methodx existing classes, consider multiple inheritance:

class a: def methoda(self): homecoming 5 class b: def methodb(self): homecoming 10 class x(): @classmethod def new(cls, baseclass): if baseclass == a: homecoming ax() elif baseclass == b: homecoming bx() else: raise exception("not supported baseclass %s!" % str(baseclass)) def methodx(self): homecoming 42 class ax(a, x): pass class bx(b, x): pass

you can add together args , kwargs x.new , pass them on specific constructors. here outputs of tests (i corrected lastly on in question):

>>> ax = x.new(a) >>> ax.methoda() # returns 5 5 >>> ax.methodx() # returns 42 42 >>> ax.methodb() # methodb not defined traceback (most recent phone call last): file "<stdin>", line 1, in <module> attributeerror: ax instance has no attribute 'methodb' >>> bx = x.new(b) >>> bx.methodb() # returns 10 10 >>> bx.new(b).methodx() # returns 42 42 >>> bx.new(b).methoda() # methoda not defined traceback (most recent phone call last): file "<stdin>", line 1, in <module> attributeerror: bx instance has no attribute 'methoda'

python oop class

No comments:

Post a Comment