note that
class Foo(object): a = None
sets a key-value pair in a Foo dict:
Foo.__dict__['a']=None
but
def __init__(self, a = None, b = None, c = None): self.a = a
sets the key-value pair in the Foo dict instance object:
foo=Foo() foo.__dict__['a']=a
Therefore, setting class members at the top of your definition is not directly related to setting instance attributes in the bottom half of your definition (inside __init__ .
Also, it's good to know that __init__ is a Python initializer. __new__ is a class constructor.
If you are looking for a way to automatically add instance attributes based on __init__ arguments, you can 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 and 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):
So when you 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 get these instance attributes:
print(foo.x)
PS. Although I wrote this (for fun), I do not recommend using autoargs for serious work. Being explicit is simple, clear, and infallible. I can not say the same for autoargs .
PPS Is it just me, or are there many buttons crashed on stackoverflow? The editor window has lost all its icons ...: ( Fixed a bug with clearing the browser cache.