2

If I create a class as below, and check the type of the object, I get the following output.

My question is what does __main__ mean here?

class Student(object):
    pass

>>>a = Student()
>>>type(a)
<class '__main__.Student'>

There is another question, if I check the type of the Student class, I get the following output.

>>>type(Student)
<class 'type'>

What does <class 'type'> mean here?

finefoot
  • 9,914
  • 7
  • 59
  • 102
Andy
  • 35
  • 1
  • 4
  • 4
    Did you try [googling and reading documentation](https://docs.python.org/3/library/__main__.html) before posting here? – DYZ Jan 03 '19 at 08:32
  • 3
    Possible duplicate of [What does if \_\_name\_\_ == "\_\_main\_\_": do?](https://stackoverflow.com/questions/419163/what-does-if-name-main-do) – Johnny Jan 03 '19 at 08:32
  • 1
    I read that before. I have two questions. Please read it carefully. In addition, I'm not quite sure if \__main__ here is same as the one in the doc. – Andy Jan 03 '19 at 08:38

2 Answers2

6

My question is what does '__main__' mean here?

__main__ there is the module in which Student is defined; the module corresponding to the file that you start with the Python interpreter is automatically named __main__. You may remember it from the usual idiom

if __name__ == '__main__':
    ...

that checks if the name of the current module is __main__ to see if this is the script that has been run (as opposed to it being imported as a module).

If you defined Student inside another file, and imported it from your main module, it would have said the name of such module instead. For example:

run.py

import student

class Student(object):
    pass

a = student.Student()
print(type(a))

b = Student()
print(type(b))

student.py

class Student(object):
    pass

if you run python run.py you'll get

<class 'student.Student'>
<class '__main__.Student'>

where you'll see confirmation that the name before the dot is indeed the module where the given type is defined (useful, as in this case, to disambiguate and to get at a glance where some given type is defined).


What does <class 'type'> mean here?

It means that the Student class, as all classes defined with class, is in turn an instance of the builtin type type. It may get a little circular, but classes themselves are instances of metaclasses; for all the gory detail about how this works under the hood, you may have a look at this question, but it isn't light reading.

Matteo Italia
  • 123,740
  • 17
  • 206
  • 299
2

The __main__ in '__main__.Student' is saying that the Student object (or class) was defined in the scope in which the top level code is being executed (the __main__ scope). If the Student class was defined in another module, call it imported_module, and imported into the main scope, then the print(type(a)) would output imported_module.Student. So basically, the type of an object always refers back to the scope in which it was defined.

Matteo Italia
  • 123,740
  • 17
  • 206
  • 299