The "class object" prints its name using `.__ name__`, despite the absence of the attribute` __name__`

The object_class name is accessible via .__name__ . See codes:

 >>> object <class 'object'> >>> object.__name__ 'object' 

However, the __name__ parameter is not in class_object by default.

codes:

 >>> foo = dir(object) >>> foo ['__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__'] >>> foo.count('__name__') 0 # '__name__' is not in list 

the object is the base for all classes. It has methods that are common to all instances of Python classes.

Where is the __name__ parameter located in?

+4
source share
2 answers

After the class body is executed, Python will automatically populate some attributes. This includes __name__ , but also __doc__ , __qualname__ (Python 3.4+) and __module__ . A complete list of these automatic attributes is available as a table in the inspect module documentation :

 Type Attribute Description class __doc__ documentation string __name__ name with which this class was defined __qualname__ qualified name __module__ name of module in which this class was defined 

They are defined by the base metaclass of Python: type classes (see also @Szabolcs answer ).

 >>> '__name__' in dir(object.__class__) True 
+6
source

Well the object built with type , so you can find __name__ in dir(type) :

 >>> '__name__' in dir(type) True 

Docs: https://docs.python.org/2/library/functions.html#type

+1
source

Source: https://habr.com/ru/post/1270779/


All Articles