4

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?

AbstProcDo
  • 19,953
  • 19
  • 81
  • 138
  • I found this to be really interesting so I decided to try to figure out how this whole thing works. I've posted an answer on the marked dupe for anyone who might be interested in digging a little deeper (and/or correcting my current understanding of how the CPython interpreter works) – mgilson Aug 11 '17 at 12:43
  • `type` inherit form 'class object', `>>> type.__bases__ (,)` – AbstProcDo Aug 11 '17 at 12:43

2 Answers2

6

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
MSeifert
  • 145,886
  • 38
  • 333
  • 352
1

Well object is constructed 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

Szabolcs
  • 3,990
  • 18
  • 38
  • the inheritances are also show with `dir`. I though so too initially. – Ma0 Aug 11 '17 at 11:26
  • 3
    ... but `type.__name__` results in `'type'`, not `'object'` -- is it a descriptor? – mgilson Aug 11 '17 at 11:29
  • 3
    @Ev.Kounis -- Also, careful here. `object` doesn't inherit from `type` -- `object`'s `type` (i.e. metaclass) is `type`. – mgilson Aug 11 '17 at 11:33
  • 1
    Yes,`type` inherits from `class object`,`>>> type.__bases__ (,) `this is the paradox about attribute `__name__`'s absence.@mgilson – AbstProcDo Aug 11 '17 at 12:56