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 には統一されたオブジェクト階層がありません (つまり、すべてがオブジェクト クラスから派生しているわけではありません)。この階層の一部は を介し​​て再生できますが、__class__そうでないものはこの方法で変更することはできません (またはまったく変更できません)。これらは Python の「型」と呼ばれ、C でハードコーディングされstrintいます。型のインスタンスの追加、削除、または型のメソッドの変更などはできません。次のトランスクリプトは、(ハードコードされた非動的な C コンストラクト) などの型と、私が A と呼んだクラスとの間の動作の違いを示しています。および B (変更可能で動的な Python コンストラクト):floatlisttuplestr

>>> 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 に答える