python - where is the instancemethod decorator? -
in code have method returns instance of class, this:
class myclass: def fun( self, *args ): # method return props( self, *args ) class props: # returned object def __init__( self, parent, *args ): self.parent = parent self.args = args to keep things organized considering place props inside myclass. bypass fun , directly make class instance method of myclass, this:
class myclass: @instancemethod # not exist! class fun: def __init__( self, parent, *args ): self.parent = parent self.args = args note comment - instancemethod decorator not exist.
is there way this, i.e. turn callable object instance method? if change @instancemethod @classmethod construction works, except of course parent class, not instance. surprised cannot find seems opposite operation.
curious have cleared up!
edit:
it seems question not clear. have member function, fun, returns not single value or tuple object full of data. data generated based on contents of myclass object , function arguments. initial code want. second code how prefer write it.
moreover noticed decorator looking following:
def instancemethod( cls ): def f( *args ): return cls( *args ) return f it is, of course, identical 'fun' method aimed bypass. note trivial 'return cls' not identical, though might seem @ first sight.
with decorator, second class definition valid , produces desired result, namely, a.fun() returns object (potentially) initialized based on data in a:
a = myclass() p = a.fun(1,2,3) print # <__main__.myclass instance @ 0xb775b84c> print p.parent # <__main__.myclass instance @ 0xb775b84c> print p.args # (1, 2, 3) this still leaves me question if instancemethod defined here not available python builtin, because seems omission next classmethod , staticmethod. but, if not, suppose can live construction.
i'm not sure you're trying do, suspect want read on descriptors.
basically, descriptor attribute of class class defines __get__ , __set__ methods. in case, move code props.__init__ props.__set__, set props fun attribute of class, , should work want.
Comments
Post a Comment