constructor - Automatically setting class member variables in Python -
say, have following class in python
class foo(object): = none b = none c = none def __init__(self, = none, b = none, c = none): self.a = self.b = b self.c = c
is there way simplify process? whenever add new member class foo, i'm forced modify constructor.
please note
class foo(object): = none
sets key-value pair in foo
's dict:
foo.__dict__['a']=none
while
def __init__(self, = none, b = none, c = none): self.a =
sets key-value pair in foo instance object's dict:
foo=foo() foo.__dict__['a']=a
so setting class members @ top of definition not directly related setting of instance attributes in lower half of definition (inside __init__
.
also, aware __init__
python's initializer. __new__
class constructor.
if looking way automatically add instance attributes based on __init__
's arguments, use this:
import inspect import functools def autoargs(*include,**kwargs): def _autoargs(func): attrs,varargs,varkw,defaults=inspect.getargspec(func) def sieve(attr): if kwargs , attr in kwargs['exclude']: return false if not include or attr in include: return true else: return false @functools.wraps(func) def wrapper(self,*args,**kwargs): # handle default values attr,val in zip(reversed(attrs),reversed(defaults)): if sieve(attr): setattr(self, attr, val) # handle positional arguments positional_attrs=attrs[1:] attr,val in zip(positional_attrs,args): if sieve(attr): setattr(self, attr, val) # handle varargs if varargs: remaining_args=args[len(positional_attrs):] if sieve(varargs): setattr(self, varargs, remaining_args) # handle varkw if kwargs: attr,val in kwargs.iteritems(): if sieve(attr): setattr(self,attr,val) return func(self,*args,**kwargs) return wrapper return _autoargs
so when say
class foo(object): @autoargs() def __init__(self,x,path,debug=false,*args,**kw): pass foo=foo('bar','/tmp',true, 100, 101,verbose=true)
you automatically these instance attributes:
print(foo.x) # bar print(foo.path) # /tmp print(foo.debug) # true print(foo.args) # (100, 101) print(foo.verbose) # true
ps. although wrote (for fun), don't recommend using autoargs
serious work. being explicit simple, clear , infallible. can't same autoargs
.
pps. me, or lot of buttons broken on stackoverflow? editor window has lost icons... :( clearing browser cache fixed problem.
Comments
Post a Comment