I need a small help with slots.
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)
Don't be confused with those string type and ENCODINGS dictionary: they are constants. The problem is that the following commands don't work as I expect:
>>> 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)
What's wrong? I'd really like to leave my class immutable, so solutions with the removing of slots are really not very good ones. :-) Thanks a lot!