0

I know how to use magical methods in python, but I would like to understand more about them.

For it I would like to consider three examples:

1) __init__:

We use this as constructor in the beginning of most classes. If this is a method, what is the object associated with it? Is it a basic python object that is used to generate all the other objects?

2) __add__ We use this to change the behaviour of the operator +. The same question above.

3) __name__: The most common use of it is inside this kind of structure:if __name__ == "__main__":

This is return True when you are running the module as the main program.

My question is __name__ a method or a variable? If it is a variable what is the method associated with it. If this is a method, what is the object associated with it?

Since I do not understand very well these methods, maybe the questions are not well formulated. I would like to understand how these methods are constructed in Python.

1
  • 2
    In a nutshell, Python does certain things at certain times with things named a certain way. Those “certain names” are virtually all such dunder-scored words, which is the convention for “Python’s special stuff”. __init__ gets called, if present, around object construction time. A module’s __name__ is set by the system, etc… Commented Sep 19, 2019 at 19:16

2 Answers 2

2
  • __init__ is not a constructor; it is an initializer, invoked automatically (usually) on the return value of __new__ (which is a constructor).

    x = Foo() is roughly equivalent to

    x = Foo.__new__(Foo) Foo.__init__(x) 
  • x + y is equivalent to x.__add__(y) or type(x).__add__(x, y)

  • __name__ is not a method; it's a str-valued module-level attribute that contains the name of the current module.

Sign up to request clarification or add additional context in comments.

Comments

1
  1. The object is the class that's being instantiated, a.k.a. the Foo in Foo.__init__(actual_instance)
  2. In a + b the object is a, and the expression is equivalent to a.__add__(b)
  3. __name__ is a variable. It can't be a method because then comparisons with a string would always be False since a function is never equal to a string

3 Comments

Yeah, I don't see that much difference between our two answers. (Clearly, two different voters involved.)
That first statement certainly seems weird… Do you mean self is not the instance? Otherwise, what “the object” do you mean?
@deceze, "the object" was meant to be the Foo in Foo.__init__(instance), and self is the argument

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.