Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatically initialize instance variables?

I have a python class that looks like this:

class Process:     def __init__(self, PID, PPID, cmd, FDs, reachable, user): 

followed by:

        self.PID=PID         self.PPID=PPID         self.cmd=cmd         ... 

Is there any way to autoinitialize these instance variables, like C++'s initialization list? It would spare lots of redundant code.

like image 934
Adam Matan Avatar asked Sep 07 '09 12:09

Adam Matan


People also ask

Are instance variables automatically initialized?

Instance variables of numerical type (int, double, etc.) are automatically initialized to zero if you provide no other values; boolean variables are initialized to false; and char variables, to the Unicode character with code number zero. An instance variable can also be a variable of object type.

Does Python automatically initialize variables?

For Python 3.7+ you can use a Data Class, which is a very pythonic and maintainable way to do what you want. It allows you to define fields for your class, which are your automatically initialized instance variables.

Does Java automatically initialize all variables?

Java does not initialize non-array local variables (also referred to as automatic variables) . The Java compiler generates error messages when it detects attempts to use uninitialized local variables. The Initializer program shows how automatic initialization works.

What method is used to initialize the instance variable of a class?

A constructor is typically used to initialize instance variables representing the main properties of the created object.


1 Answers

You can use a decorator:

from functools import wraps import inspect  def initializer(func):     """     Automatically assigns the parameters.      >>> class process:     ...     @initializer     ...     def __init__(self, cmd, reachable=False, user='root'):     ...         pass     >>> p = process('halt', True)     >>> p.cmd, p.reachable, p.user     ('halt', True, 'root')     """     names, varargs, keywords, defaults = inspect.getargspec(func)      @wraps(func)     def wrapper(self, *args, **kargs):         for name, arg in list(zip(names[1:], args)) + list(kargs.items()):             setattr(self, name, arg)          for name, default in zip(reversed(names), reversed(defaults)):             if not hasattr(self, name):                 setattr(self, name, default)          func(self, *args, **kargs)      return wrapper 

Use it to decorate the __init__ method:

class process:     @initializer     def __init__(self, PID, PPID, cmd, FDs, reachable, user):         pass 

Output:

>>> c = process(1, 2, 3, 4, 5, 6) >>> c.PID 1 >>> dir(c) ['FDs', 'PID', 'PPID', '__doc__', '__init__', '__module__', 'cmd', 'reachable', 'user' 
like image 137
Nadia Alramli Avatar answered Sep 28 '22 02:09

Nadia Alramli