python - Initializing a class that consist of many classes in such a way that one of the classes has different attributes -
here classes , relations:
http://i.imgur.com/hs5yrzz.png
code clarification:
class a(object): def __init__(self): self.atr = 1 class b(object): def __init__(self): self.atr = a() class c(object): def __init__(self): self.atr = a() class d(object): def __init__(self): self.atr1 = b() self.atr2 = c() test1 = d()
now do if want initialize d
in such way a
's self.atr = 2
, , change reflects classes (b
, c
) use a
when initialize d
like imagine in pseudo code:
test2 = d(a.self.atr = 2)
so initialize d
in such manner a
's self.atr = 2
if want b , c have different properties, required call d, way pass parameters initialization of b , c know do.
the parameter can instance of a, attributes care set before inistantiatin b , c:
class a(object): def __init__(self, atr=1): self.atr = atr class b(object): def __init__(self, config): self.atr = config class c(object): def __init__(self, config): self.atr = config class d(object): def __init__(self): my_a = a(2) self.atr1 = b(my_a) self.atr2 = c(my_a) test1 = d()
update see comments above seem dislike approach duew impression you'd have lot of repetitive code everywhere - not case - if example, have lot of classes have "preconfigured" class a, passed lot of other classes, create bundle of classes pre-configured - you'd still pass on single parameter each instance create.
also, there are, want, mechanisms in python allow dynamically reconfiguring classes - using "variables" being 1 of them - probelm doing in naive way want, you'd ahve pretty unmaintainable mess.
for example, if use module-level (= global) variable "1" instead of hardcoding a, do:
current_atr_value = 1 class a(object): def __init__(self): self.atr = current_atr_value class b(object): def __init__(self): self.atr = a() class c(object): def __init__(self): self.atr = a() class d(object): def __init__(self, atr): global current_atr_value old = current_atr_value current_atr_value = atr self.atr1 = b() self.atr2 = c() current_atr_value = old test1 = d(atr=2)
this have thge exact effect intending, not simpler - whithout requiring of language's advanced introspection capabilities, , still lead unmaintainable mess. way passing parameters around contain custom values in scopes wanted, without side-effects, not in multi-threading or multi-processing running environment, , far more recomendable.
if want mess things around, create factory function produce new class "a" desired attributes, , inject in module global namespace new "a" class while instantiate others - "fancier" , maybe you'd like. write inside like:
def a_factory(atr=1): class a(object): def __init__(self, atr=1): self.atr = atr globals()["a"] = # creates default "a" class a_factory(1)
and call factory desired "atr" while instantiating "b" , "c" above. absolutely unmanageable, asking for. t
Comments
Post a Comment