Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does 'del self.self ' in an __init__ function mean?

Tags:

python

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>
like image 707
Sophie Lovegood Avatar asked Aug 05 '19 22:08

Sophie Lovegood


People also ask

What does __ init __( self mean?

__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.

What does self do in init function?

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.

What does __ init __ function do?

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.

What is __ self __ in Python?

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.


2 Answers

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
like image 175
Dan D. Avatar answered Oct 12 '22 21:10

Dan D.


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.

like image 22
khelwood Avatar answered Oct 12 '22 22:10

khelwood