Discuss / Python / 作业

作业

Topic source
class Screen(object):
    @property
    def width(self):
        return self._width
    @width.setter
    def width(self,x):
        if not isinstance(x,(int,float)):
            raise ValueError('width must be a number')
        elif x<=0:
            raise ValueError('width must lager than 0')
        else:
            self._width=x


    @property
    def height(self):
        return self._height
    @height.setter
    def height(self,value):
        if not isinstance(value,(int,float)):
            raise ValueError('height must be a number')
        elif value<=0:
            raise ValueError('height must lager than 0')
        else:
            self._height=value

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

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

开始不太懂assert是干嘛的 百度了一下才明白原来是判断用

另外用isinstance判断是否以或的关系满足两个条件,开始用 isinstance(x,int or float) 发现只能在符合int及第一个条件时执行,如果x是float会判断为False。 但如果用isinstance(x,int and float)会判断第二个条件。x为int时会返回False。

AlWays_MU

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

这个问题让我想起刚看python的时候,看到逻辑判断and or not有个很有趣的事,总是把C里面的情况代入进来。 你试试:

1 and 0                #返回 0
1 and 2                #返回 2

1 or 0                #返回 1
1 or 2                #返回 2

所以python里和C不一样:

int and float #返回 float
int or float  #返回 int

  • 1

Reply