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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With