问题
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?
回答1:
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.
回答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.
来源:https://stackoverflow.com/questions/54018653/what-does-main-mean-in-the-output-of-type