简体   繁体   中英

__slots__ and unbound methods

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!

You want to use __init__ , not __new__ .

__new__ is a class method for which the first argument (self) is the class object, not the newly created object. It has to return the new object. You usually don't want to redefine it, but you can if you want to do things like return an existing object.

__init__ is a regular instance method, and the first argument (self) is the newly created instance. It works like constructors in other languages.

To fix this, change the method name to __init__ and delete the final line ( return(self) ). __init__ . must always return None ; returning anything else results in a TypeError .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM