inheritance - Python super override object name -
i'm trying extend framework, have this:
class a(object): def test(self): print(1) class b(object): def method(self): = a() a.test() class customa(a): def test(self): print(2) class c(b): def method(self): = customa super(c, self).method() c = c() c.method()
classes , b framework.
i want edit test() a, , make c use new method.
in code, example, how can make code print 2 instead of 1?
[update]
this simple example. want extend this class. instead of create settingspanel
, create customsettingspanel
but problem i'll need lot of classes, want way make python use customsettingspanel
, not settingspanel
.
there's lot of ways approach problem.
if can edit b
, refactor instead of hard dependency on a
, have accept parameter in ___init___
allow 1 specify class instantiate. like:
class b(object): def __init___(self, clazz=a): self.__clazz = clazz def method(self): = self.__clazz() a.test() class c(b): def __init__(self): super(c, self).__init__(customa)
if can't edit b
, i'd suggest wrapping in adapter, have code interact through class (rather b
or c
) , manage complexity of a
vs customa
choice there in adapter via flag parameter:
class abcadapter(object): use_class_a = 0 use_class_customa = 1 def __init__(self, test_class=use_class_a): if test_class = use_class_a: self.a_instance = a() elif test_class = use_class_customa: self.a_instance = customa() def method(self): self.a_instance.test()
could other object creational patterns (factories, etc). depends on constraints , you're trying accomplish.
Comments
Post a Comment