【发布时间】:2012-07-26 13:42:27
【问题描述】:
我在插槽方面需要一点帮助。
class bstream(object):
__slots__ = ['stream']
stream = string()
def __new__(self, stream, encoding=None):
if encoding == None:
encoding = ENCODING['default']
if isinstance(stream, bytes):
self.stream = stream.decode(encoding)
elif isinstance(stream, string):
self.stream = stream
else: # if unknown type
strtype = type(stream).__name__
raise(TypeError('stream must be bytes or string, not %s' % strtype))
return(self)
def __repr__(self):
'''bstream.__repr__() <==> repr(bstream)'''
chars = ['\\x%s' % ('%02x' % ord(char)).upper() for char in self.stream]
result = ''.join(chars)
return(result)
def func(self):
return(1)
不要与那些字符串类型和 ENCODINGS 字典混淆:它们是常量。 问题是以下命令无法按我的预期工作:
>>> var = bstream('data')
>>> repr(var)
<class '__main__.bstream'> # Instead of '\\x64\\x61\\x74\\x61'
>>> var.func()
TypeError: unbound method func() must be called with bstream instance as first argument (got nothing instead)
怎么了?我真的很想让我的班级不可变,所以删除 slots 的解决方案真的不是很好。 :-) 非常感谢!
【问题讨论】:
-
为什么?
__slots__相当没用,尤其是在您知道自己需要它之前。这是使您的类不可变的一种糟糕方法,为此,不要对其进行变异(或不提供公共 API 来对其进行变异)。 -
@Julian:你说得对,我已经将它定义为使类不可变。之前我总是使用 Cython 做同样的事情,但它不像 Python 那样可移植。
-
为什么你希望类是不可变的?如果您不想更改,请不要更改它。你正在努力对抗 Python。
-
看看this answer,你可能不想要
__slots__,我也真的不认为你想要__new__。 -
@D.Shawley:它已经在 Python 3 中了。我使用它是因为它仍然是用户尝试设置属性时避免错误的最佳方法。这也是减少 Python 在处理对象时所需内存的好方法。
标签: python class immutability slots