Jua*_*nti 15 python python-datamodel
我希望能够做到:
>>> class a(str):
... pass
...
>>> b = a()
>>> b.__class__ = str
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: __class__ assignment: only for heap types
Run Code Online (Sandbox Code Playgroud)
I've solved it in this way:
>>> class C(str):
... def __getattribute__(self, name):
... if name == '__class__':
... return str
... else:
... return super(C, self).__getattribute__(name)
...
>>> c = C()
>>> c.__class__
<type 'str'>
Run Code Online (Sandbox Code Playgroud)
小智 5
Python 2没有统一的对象层次结构(即,并非所有内容都来自对象类).任何属于此层次结构的东西都可以使用via来播放__class__,但那些不能以这种方式进行修改(或者根本不是这样).这些被称为Python的"类型",并在C的类型实例他们硬编码str,int,float,list,tuple,等.这意味着你不能在相同的方式作为类使用类型,例如,你不能改变类对于类型的实例,您不能添加,删除或修改类型的方法等.以下的脚本显示了类型之间的行为差异,例如str(硬编码,非动态C构造)和我称之为A的类和B(可变,动态,Python构造):
>>> str
<type 'str'>
>>> class A:
... pass
...
>>> a = A()
>>> A
<class __main__.A at 0xb747f2cc>
>>> a
<__main__.A instance at 0xb747e74c>
>>> type(a)
<type 'instance'>
>>> type(A)
<type 'classobj'>
>>> type(str)
<type 'type'>
>>> type(type(a))
<type 'type'>
>>> type(type(A))
<type 'type'>
>>> A.foo = lambda self,x: x
>>> a.foo(10)
10
>>> A().foo(5)
5
>>> str.foo = lambda self,x: x
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can't set attributes of built-in/extension type 'str'
>>> 'abc'.foo(5)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute 'foo'
>>> class B:
... pass
...
>>> a.__class__
<class __main__.A at 0xb747f2cc>
>>> a.__class__ = B
>>> a
<__main__.B instance at 0xb747e74c>
>>> 'abc'.__class__
<type 'str'>
>>> 'abc'.__class__ = B
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: __class__ must be set to new-style class, not 'classobj' object
>>> class B(object):
... pass
...
>>> 'abc'.__class__ = B
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: __class__ assignment: only for heap types
Run Code Online (Sandbox Code Playgroud)