What does first argument to `type` do?
Some code.
In [1]: A = type('B', (), {})
In [2]: a = A()
In [3]: b = B()
---------------------------------------------------------------------------开发者_运维知识库
NameError Traceback (most recent call last)
/home/shabda/<ipython console> in <module>()
NameError: name 'B' is not defined
What does first argument to type
doing here?
It's setting the __name__
property of the created class.
When you say:
class B(object):
two things happen with that 'B':
The name 'B' is assigned the class. This is just like if you'd said "
B = ...
".The
__name__
property of the class is set to 'B'.
When you invoke the type constructor manually only the latter half is done. If you don't assign the result to 'B' then B will remain set (or unset) as it was before.
Note that a similar result could be obtained by saying:
class B(object):
pass
A = B
del B
Now A refers to a class that calls itself 'B', and B doesn't refer to anything.
It's creating a new class with the name B
:
Python 2.5.4 (r254:67916, Nov 19 2009, 22:14:20)
[GCC 4.3.4] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> type('B', (), {})
<class '__main__.B'>
See the second form of type
here for more information.
When you assign the result of calling type
to a variable, you're just giving the class B
another name. It's equivalent to doing
>>> class B(object):
... pass
...
>>> A = B
>>> a = A()
>>> b = B()
'B' is just a string which is the name of A
One place it is used is for the default __repr__
of classes and their objects
>>> A=type('B', (), {})
>>> A
<class '__main__.B'>
>>> a=A()
>>> a
<__main__.B object at 0xb7cf88ec>
The usual way to create a class has no way to explicitly set the __name__
attribute.
In this case it is implicitly set by the class constructor
>>> class A:pass
...
>>> A
<class __main__.A at 0xb7cf280c>
But there is nothing stopping you from changing the name afterward
>>> A.__name__
'A'
>>> A.__name__='B'
>>> A
<class __main__.B at 0xb7cf280c>
>>>
精彩评论