I have a StatsVar class to maintain the statistic variable, and a Ctx class to register the statistic variables as its attributes as follows.
class StatsVar:
def __init__(self, v):
self.v = v
class Ctx:
def __init__(self):
self.vars = list()
def register(self, v):
self.vars.append(v)
Create a StatsVars and register into an instance of Ctx by the following code:
ctx = Ctx()
var = StatsVar(0.)
ctx.register(var)
What I want to do:
- use a decorator to register the new instance of
StatsVarintoctx(Rather thanCtx)
However, I don't know how to obtain the instance of Ctx (like self) to run self.vars.append(v) in the following code:
@Ctx.register
class StatsVar:
def __init__(self, v):
self.v = v
class Ctx:
def __init__(self):
self.vars = list()
def register(cls):
def wrapper(v):
# !!! HERE, I know it's wrong, but how to obtain `self`?
self.vars.append(v)
return cls(v)
return wrapper
Update
I found a feasible solution is to place StatsVar as an inner class and the creation of StatsVar is left to the instance of Ctx as follows:
class Ctx:
def __init__(self):
self.vars = list()
def statsvar(self):
manager = self
class StatsVar:
def __init__(self, v):
self.v = v
manager.vars.append(v)
return StatsVar
if __name__ == '__main__':
ctx = Ctx()
ctx.statsvar()(0.)
print('')
However, calling ctx.statsvar()(0.) seems terrible and is there any better solution here?
Ctxclass and then passes it back. I know that's not quite how you want it.Ctx? If not, perhaps you should create the instance before definingStatsVarso you can add the instances of the latter to the single instance of the former. Or you could do without theCtxclass all together, and just use global functions and variables. If you do want to be able to have multpleCtxinstances, then it's going to be very hard for any decorator to do anything useful since there's no clear way for it to know whichCtxinstance to register a newStatsVarinstance to.@classmethodCtxshould be defined before theStatsVarto perform sugar decoration