I see someone's code this way:
class SomeClass(ParentClass):
def __init__(
self,
attribute_1,
attribute_2
):
self.__dict__.update(locals())
del self.self
I can understand the first line -- adding new attributes to the ParentClass
' attribute dictionary. But what is del self.self
?
I tried to see what self.self
is.
It is exactly THAT self. Why should one delete the object in its __init__
function? When I stepped out __init__
, I found the object still existed with the same address.
self
Out[2]: <classname at 0x244ee3f6a90>
self.self
Out[3]: <classname at 0x244ee3f6a90>
self.self.self
Out[4]: <classname at 0x244ee3f6a90>
__init__ is the constructor for a class. The self parameter refers to the instance of the object (like this in C++). class Point: def __init__(self, x, y): self._x = x self._y = y.
The self in keyword in Python is used to all the instances in a class. By using the self keyword, one can easily access all the instances defined within a class, including its methods and attributes. __init__ is one of the reserved methods in Python. In object oriented programming, it is known as a constructor.
The __init__ method is the Python equivalent of the C++ constructor in an object-oriented approach. The __init__ function is called every time an object is created from a class. The __init__ method lets the class initialize the object's attributes and serves no other purpose. It is only used within classes.
self represents the instance of the class. By using the “self” we can access the attributes and methods of the class in python. It binds the attributes with the given arguments. The reason you need to use self. is because Python does not use the @ syntax to refer to instance attributes.
The line: self.__dict__.update(locals())
results in three names being bound as attributes of self
: self
, attribute_1
, attribute_2
. The del self.self
simply removes the unwanted self attribute on the object named by the name self.
This is lazy. It would be better to simply have the two lines:
self.attribute_1 = attribute_1
self.attribute_2 = attribute_2
self
is a local variable, so it appears in locals()
.
self.__dict__.update(locals())
adds an attribute to the new object for every local variable, including self
. Since that attribute is apparently not required, it gets deleted.
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