17

我希望能够做到:

>>> 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
4

4 回答 4

7

我以这种方式解决了它:

>>> 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'>
于 2010-06-14T07:46:27.870 回答
6

Python 2 没有统一的对象层次结构(即,并非所有内容都来自对象类)。任何属于这个层次结构的东西都可以通过 via 播放__class__,但不能以这种方式修改(或者根本不能修改)。这些被称为 Python 的“类型”,它们在 C 中被硬编码。类型的示例是strintfloatlisttuple等。这意味着您不能以与类相同的方式使用类型,例如,您不能更改类对于类型的实例,您不能添加、删除或修改类型的方法等。以下记录显示了类型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
于 2011-03-26T15:30:33.297 回答
-1

只有用class关键字定义的类才能用于__class__属性分配:

>>> class C:
    pass

>>> class D:
    pass

>>> C().__class__ = D
>>>
于 2010-06-10T09:54:15.787 回答
-2

我试过这种方法!

>>> class C(str):
...     __class__ = str
...
>>> c = C()
>>> c.__class__
<class 'str'>
于 2019-03-05T14:52:58.557 回答