使用__new __()在Python中创建不可变类型

Anl*_*ler 1 python datamodel

我的问题很简单,我有:

class upperstr(str):
    def __new__(cls, arg):
        return str.__new__(cls, str(arg).upper())
Run Code Online (Sandbox Code Playgroud)

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

>>> s = str("text")
>>> "__dict__" in dir(s)
False
>>> s = upperstr("text")
>>> "__dict__" in dir(s)
True
Run Code Online (Sandbox Code Playgroud)

如果我只重写__new __()方法,解释器在什么阶段将__dict__属性设置为upperstr intances?

谢谢!

Sve*_*ach 7

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

>>> 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__
{}
Run Code Online (Sandbox Code Playgroud)

如果你不想要一个新式的类__dict__,请使用__slots__(文档,相关的SO线程):

>>> 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__'
Run Code Online (Sandbox Code Playgroud)