I would like to know if there is some downside or good reason not to define inner nested classes inside the __init__
of the outer class like shown below. I am considering this approach for my library API.
What I like about it is that the behavior of inner classes could be customized directly on subclasses of Outer and I have access to the Outer objects in each Inner class via self
. Also I could define defaults on class level for each inner class but those defaults may be different for each instance of Outer.
class Outer:
def __init__(self):
class Inner1:
param = 42 # default
def __init__(inner, param=None):
if param is not None:
inner.param = param
def do_something(inner):
print(inner.param)
self.inner1 = Inner1
class OuterSub(Outer):
def __init__(self):
super().__init__()
class Inner1(self.inner1):
def do_something(inner):
print(2*inner.param)
self.inner1 = Inner1
outer = Outer()
outer_sub = OuterSub()
outer.inner1(2).do_something()
outer_sub.inner1.param = 5
outer_sub.inner1().do_something()
Aucun commentaire:
Enregistrer un commentaire