Python 官方文档:入门教程 => 点击学习
@property广泛应用在类的定义中,可以让调用者写出简短的代码,同时保证对参数进行必要的检查,这样,程序运行时就减少了出错的可能性。详见链接:廖雪峰python3使用@property练习请利用@property给一个Screen对象加
@property
广泛应用在类的定义中,可以让调用者写出简短的代码,同时保证对参数进行必要的检查,这样,程序运行时就减少了出错的可能性。详见链接:廖雪峰python3使用@property
请利用@property
给一个Screen
对象加上width
和height
属性,以及一个只读属性resolution
:
#_*_ coding: utf-8 _*_
class Screen(object):
@property
def width(self):
return self._width
@width.setter
def width(self,value):
if not isinstance(value,int):
raise ValueError(' value is wrong type,it need int')
if value < 0:
raise ValueError('value must > 0')
self._width = value
@property
def height(self):
return self._height
@height.setter
def height(self,value):
if not isinstance(value,int):
raise ValueError(' value is wrong type,it need int')
if value < 0:
raise ValueError('value must > 0')
self._height = value
@property
def resolution(self):
self._resolution = self._height * self._width
return self._resolution
s= Screen()
s.width = 1024
print(s.width)
s.height = 768
print(s.height)
print(s.resolution)
--结束END--
本文标题: python @property用法作用
本文链接: https://www.lsjlt.com/news/185423.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-03-01
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0