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

时间:2011-11-26 12:32:57

标签: python datamodel

我的问题很简单,我有:

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

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

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

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

谢谢!

1 个答案:

答案 0 :(得分:7)

默认情况下,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__documentationrelated 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__'