Discuss / Python / 求大神帮我看看

求大神帮我看看

Topic source
class Screen(object):

    @property
    def width(self):
        return self._width

    @width.setter
    def width(self,width):
        self._width=width

    @property
    def height(self):
        return self._height

    @height.setter
    def height(self,height):
        self._height=height

    @property
    def resulution(self):
        return self._width*self._height

s=Screen()
s.width=1024
s.height=768
print(s.width)
print(s.height)
print(s.resulution)
assert s.resolution == 786432, '1024 * 768 = %d ?' % s.resolution

执行assert的时候,报错了:

D:\1学习笔记\05Python\0615>property.py
1024
768
786432
Traceback (most recent call last):
  File "D:\1学习笔记\05Python\0615\property.py", line 29, in <module>
    assert s.resolution == 786432, '1024 * 768 = %d ?' % s.resolution
AttributeError: 'Screen' object has no attribute 'resolution'

为神马会报这个错误!

还有下面代码居然没有报错:

#为什么下面两句仍然可以执行?说好的是只读呢?难道是我设置的姿势不对?
s.resolution=1990
print(s.resolution)

Charlcas

#2 Created at ... [Delete] [Delete and Lock User]

因为你写错了, @property def resulution(self): return self._width*self._height

宋洪基

#3 Created at ... [Delete] [Delete and Lock User]

对啊,resolution写成了resulution了。 单独执行下面的语句可以,是因为你动态增加了resolution属性(它并不是只读的,根据你的定义只有resulution是只读的)。 s.resolution=1990 print(s.resolution)


  • 1

Reply