Discuss / Python / 交作业

交作业

Topic source

___Hiboboo

#1 Created at ... [Delete] [Delete and Lock User]
# -*- coding: utf-8 -*-


class Screen(object):

    def __init__(self):
        self.__width = None
        self.__height = None
        self.__resolution = None

    __slots__ = ("__width", "__height", "__resolution")

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

    @width.setter
    def width(self, width):
        if not isinstance(width, (int, float)):
            raise ValueError("width must be an integer or float!")
        if width in (320, 480, 540, 720, 1080, 1440):
            self.__width = width
        else:
            raise ValueError("width (320, 480, 540, 720, 1080, 1440)!")

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

    @height.setter
    def height(self, height):
        if not isinstance(height, (int, float)):
            raise ValueError("height must be an integer or float!")
        if height in (480, 800, 960, 1280, 1920, 2560):
            self.__height = height
        else:
            raise ValueError("height (480, 800, 960, 1280, 1920, 2560)!")

    @property
    def resolution(self):
        return self.__width * self.__height


# 测试:
s = Screen()
s.width = 1080
s.height = 1920
print('resolution =', s.resolution)
if s.resolution == 2073600:
    print('测试通过!')
else:
    print('测试失败!')

风雪扑面

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

__init__里定义过实例的3个属性,__slots__的tuple是否可以留个空

夏夏夏SR

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

你这里的width和height,定义完之后外部能访问到吗?不是定义成私有属性了吗

___Hiboboo

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

@夏夏夏SR

你这么问的话,说明你对这章的学习没有了解啊,建议再仔仔细细看一遍今天老师讲的内容。 注意要理解@property是干啥的?为什么用它?它的内部实现又是怎样的?


  • 1

Reply