Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python oop: __init__ methods of class have often trivial assignments self.value=value

Tags:

python

oop

Often python classes have following form of __init__ methods:

class myclass:
     def __init__(self, value):
        self.value = value

The trivial assignment of method parameter and instance variable feels like unnecessary code. As far as I understand, following does not work:

class myclass:
     def __init__(self, self.value):
        pass

and I always have to write __init__ methods with these trivial assignments.

Is this correct?

like image 297
Hotschke Avatar asked Dec 10 '22 18:12

Hotschke


2 Answers

It's not just performing an assignment; it's also essentially doubling as the "declaration" of your instance variables. Yes, there's nothing stopping you from adding more instance variables at any time during the life of the object, but by convention, the attributes you assign to in __init__ provide the de facto definition of what attributes are available on an instance of the class.

like image 52
chepner Avatar answered Jun 04 '23 04:06

chepner


I have used the following for many years now:

def MyClass:
    def __init__(self, some_var, some_other_var, some_kwarg=None):
        self.__dict__.update(locals())

To me, this clearly shows that I want to declare all the variables passed to __init__ to be instance variables, but it might not be so for someone unfamiliar with Python's classes, so use it warily.

What it does, essentially, is to push all local--scope variables to the instance's variable dictionary. You can even combine it with **kwargs (using Python 3.5 syntax):

def MyClass:
    def __init__(self, some_var, some_other_var, some_kwarg=None, **kwargs):
        self.__dict__.update({**locals(), **kwargs})

to allow arbitrary keyword arguments to be pushed into the instance's variable scope, though I highly discourage this usage for most purposes.

like image 32
dalum Avatar answered Jun 04 '23 03:06

dalum