i have 2 python classes defined follows :
class a(object) : def __init__(self, param) : print('a.__init__ called') self.param = param def __new__(cls, param) : print('a.__new__ called') x = object.__new__(a) x._initialize() # initialization code return x class b(a) : def __init__(self, different_param) : print('b.__init__ called') def __new__(cls, different_param) : print('b.__new__ called') # call __new__ of class a, passing "param" parameter # , initialized instance of class b # below b = object.__new__(b) param = cls.convert_param(different_param) return super(b, cls).__new__(b, param) # expecting # similar @staticmethod def convert_param(param) : return param class b subclass of class a. difference between 2 classes parameters passed class b in different format compared expected class a. so, convert_param method of classb called convert parameters compatible __new__ method of class a.
i stuck @ part wish call __new__ method of class a __new__ method of class b, since there lot of initialisation takes place in there, , initialised instance of class b.
i having difficult time figuring out. please help.
convert_param should either staticmethod or classmethod , don't want calling object.__new__ b (otherwise, you're trying create 2 new instances of b instead of one). if convert_param staticmethod or classmethod, can parameter conversion before have instance (e.g. before __new__ has been called on superclass):
class b(a): @staticmethod def convert_param(params): # magic return params def __new__(cls, params): params = cls.convert_params(params) return super(b, cls).__new__(cls, params) additionally, you'll need change a's __new__ not hard-code type of instance returned object.__new__:
class a(object) : def __new__(cls, param) : print('a.__new__ called') x = super(a, cls).__new__(cls) x._initialize() # initialization code return x
Comments
Post a Comment