What does __*(any word)__ or _* mean in Python?

Asked

Viewed 1,000 times

9

Reading a book once in a while he puts __init__ or __init and I don’t know what this "_" means, I tried to search the internet some explanations, but I ended up making myself more difficult, someone could help me explaining in a more practical way?

1 answer

6


Gambiarra :)

These things were inserted into the language very late, as these identifiers might already be being used by existing Python codes needed to do something to not break existing codes and as the __ is "reserved" solved the issue.

These identifiers are for "magical" members of the language, so it’s not a common name, it’s something that the language treats in a special way and generates something specific.

The __init__ for example it is a method that will initialize the object, what you write there will be executed every time an object is instantiated. The language will call you.So it’s not just any method, its presence in your code tells the language what it should do.

The official explanation is that this is to differentiate that it is a "magic" function, but it is not consistent.

Bug Feature e By design (três baratas uma mais bem vestida e outra bem vestida mas detonada)

  • But it doesn’t make sense, that’s not why we import libraries and use them in functions afterwards?

  • But this has nothing to do with libraries, it is language building. You matter to use for, if, etc? It’s the same thing, it doesn’t add any new function, it adds something to the language.

  • Understood, I could give an example of "language treats as something special".

  • @Thinking edited.

  • 1

    -1 for the "gamibiarra". It is not - because these "things" were inserted into the language along with the object model 0 it is not as if there already existed a gigantic code base with false "init" methods. ** is purposeful to indicate methods that are called internally by the mechanisms of language, but this is an option of the design of these methods, not an "ad hoc" way of avoiding collisions.

  • Failed to comment that in object classes, methods and attributes started with _ (or __, currently is preferring to use this syntax) are not exported to new objects in case of inheritance.

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.