python - Multiple initialisation with given input parameter -
i trying make class executed given number of times according passed parameter. class converts dictionary desired data.
let me show quick example of mean exactly:
first class a
offers common methods derivative classes.
class a(object): @staticmethod def do_magic(obj): # ... print(''.obj)
class b
, e
(skipped in example) initialise objects , provide b_stuff
, e_stuff
.
class b(a): def __init__(self, mydict): # self.b_stuff = [...]
now class c
comes play. transforms given dictionary mydict
has key-value pair describing number of iterations 'iters': 'val'
class c(b, e): def __init__(self, mydict): b.__init__(self, mydict) # access b_stuff e.__init__(self, mydict) # access e_stuff self.iters = int(self.mydict['iters']) # desired nb of initialisations/executions self.c_stuff = [b_stuff, e_stuff, other] def do_magic(self): a.do_magic(self.c_stuff)
now problem is, once calling class external loop later in code don't know how make class do_magic
mydict['iters']
number of times.
for d in list_of_dicts: c(d).do_magic()
one of solutions i'll initialise class in external loop above, that:
for d in list_of_dicts: in range(int(d['iters'])) c(d).do_magic()
but feels far away oop style.
to 100% sure folks follow me, ill show here actual expected behaviour:
d
- input dictionary
d['iters'] = 2
execute
c(d).do_magic()
actual result:
>>> 'xxx yyy random_number1 .... '
expected result:
>>> 'xxx yyy random_number1 .... ' 'xxx yyy random_number2 .... ' # random number class b re-initialised!!
as exploring stack i've found out hints refer __new__
method still no clue if right path , how :)
edit:
as @peter-wood suggested - adding question:
i'd point out both attributes b_stuff
, e_stuff
once initialised - produce unique strings part of c_stuff
, updated each do_magic()
call.
this method ''.join(obj)
(see class a)
class c(b, e): def do_magic(self): _ in range(self.iters): a.do_magic(self.c_stuff)
Comments
Post a Comment