我需要一个关于slot的小帮助。
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)
怎么了?我真的很想让我的班级不可变,所以删除插槽的解决方案真的不是很好。:-) 非常感谢!