Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The 'class object' prints its name using `.__name__`,despite of the absence of `__name__` attribute [duplicate]

Tags:

python

Class_object's name is accessible through .__name__, See the codes:

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

Nevertheless, the __name__ method is not in class_object's default setting.

the 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

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

Where __name__'s setting is located in?

like image 982
AbstProcDo Avatar asked Mar 08 '23 08:03

AbstProcDo


1 Answers

After the class body is executed Python will fill in some attributes automatically. That includes __name__ but also __doc__, __qualname__ (Python 3.4+) and __module__. The complete list of these automated attributes is avaiable as 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

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

>>> '__name__' in dir(object.__class__)
True
like image 82
MSeifert Avatar answered Apr 05 '23 23:04

MSeifert