Skip to main content
 首页 » 编程设计

python之使用 __new__() 在 Python 中创建不可变类型

2025年05月04日14cyq1162

我的问题很简单,我有:

class upperstr(str): 
    def __new__(cls, arg): 
        return str.__new__(cls, str(arg).upper()) 

为什么,如果我的 __new__() 方法直接使用不可变类型 (str) 的实例,我的新类型 (upperstr) 的实例是可变的?

>>> s = str("text") 
>>> "__dict__" in dir(s) 
False 
>>> s = upperstr("text") 
>>> "__dict__" in dir(s) 
True 

如果我只是覆盖 __new__() 方法,解释器在什么阶段将 __dict__ 属性设置为 upperstr 实例?

谢谢!

请您参考如下方法:

默认情况下,Python 中所有用户定义的类都有一个 __dict__() 属性,即使您根本没有覆盖任何内容也是如此:

>>> x = object() 
>>> x.__dict__ 
Traceback (most recent call last): 
  File "<stdin>", line 1, in <module> 
AttributeError: 'object' object has no attribute '__dict__' 
>>> class MyObject(object): 
...     pass  
...  
>>> x = MyObject() 
>>> x.__dict__ 
{} 

如果您不希望新式类具有 __dict__,请使用 __slots__(documentation,related SO thread):

>>> class MyObject(object): 
...     __slots__ = [] 
...  
>>> x = MyObject() 
>>> x.__dict__ 
Traceback (most recent call last): 
  File "<stdin>", line 1, in <module> 
AttributeError: 'MyObject' object has no attribute '__dict__'