是否可以在 Python 1 或 Python 2 中创建新类型(但不是新的 class)?
Is it possible to create a new type(but not a new class) in Python 1 or Python 2?
Python 2.1.x 或更低版本中没有 object
类型。
这是三个文件:
#!/usr/bin/env python2
class foo: pass
print(foo)
print(repr(foo))
print(type(foo))
#!/usr/bin/env python2
class foo(object): pass
print(foo)
print(repr(foo))
print(type(foo))
#!/usr/bin/env python3
class foo(object): pass
print(foo)
print(repr(foo))
print(type(foo))
这是他们的输出:(仅供参考)
__main__.foo
<class __main__.foo at 0xf7d30e9c>
<type 'classobj'>
<class '__main__.foo'>
<class '__main__.foo'>
<type 'type'>
<class '__main__.foo'>
<class '__main__.foo'>
<class 'type'>
在Python3中,所有类型都是classes.
但是在Python1和Python2中,类型是“type”类型,classes是“classobj”类型。 class foo(object): pass
生成的class只是“object”类型的childclass。
那么,是否可以在 Python 1 或 Python 2 中创建一个新类型(但不是新的 class)?如果是,如何?
感谢@chepner
No, that's why new-style classes were added: to eliminate the artificial distinction between classes and types. Old-style classes have type classobj
, but they were effectively deprecated as soon as new-style classes were introduced in Python 2.2. Given the extreme age of the versions being asked about, this would probably be more suitable retrocomputing.stackexchange.com.
Python 2.1.x 或更低版本中没有 object
类型。
这是三个文件:
#!/usr/bin/env python2
class foo: pass
print(foo)
print(repr(foo))
print(type(foo))
#!/usr/bin/env python2
class foo(object): pass
print(foo)
print(repr(foo))
print(type(foo))
#!/usr/bin/env python3
class foo(object): pass
print(foo)
print(repr(foo))
print(type(foo))
这是他们的输出:(仅供参考)
__main__.foo
<class __main__.foo at 0xf7d30e9c>
<type 'classobj'>
<class '__main__.foo'>
<class '__main__.foo'>
<type 'type'>
<class '__main__.foo'>
<class '__main__.foo'>
<class 'type'>
在Python3中,所有类型都是classes.
但是在Python1和Python2中,类型是“type”类型,classes是“classobj”类型。 class foo(object): pass
生成的class只是“object”类型的childclass。
那么,是否可以在 Python 1 或 Python 2 中创建一个新类型(但不是新的 class)?如果是,如何?
感谢@chepner
No, that's why new-style classes were added: to eliminate the artificial distinction between classes and types. Old-style classes have type
classobj
, but they were effectively deprecated as soon as new-style classes were introduced in Python 2.2. Given the extreme age of the versions being asked about, this would probably be more suitable retrocomputing.stackexchange.com.