Discuss / Python / 为什么这里用不了__slots__?

为什么这里用不了__slots__?

Topic source

想用上slots,但是报错了。 class Screen(object):

#__slots__=('width','height','resolution')
@property
def width(self):
    return self._width
@width.setter
def width(self,width):
    if not isinstance(width,int):
        print('You should enter an integer')
    else:
        self._width=width
@property
def height(self):
    return self._height
@height.setter
def height(self,height):
    if not isinstance(height,int):
        print('You should enter an integer')
    else:
        self._height=height
@property
def resolution(self):
    return self._width*self._height

去掉#就报错。 还有,为什么属性只能是self.width或self.__width,去掉‘’,用self.width,python就报错

我的理解,这里的'width', 'height', 'resolution'等价于get,set函数,应该写成 __slots__ = {'_width', '_height', '_resolution'}


  • 1

Reply