python中@property是什么

Python (183) 2023-05-22 15:35:33

说明

1、内置的@property装饰器Python负责将一种方法转换为属性调用。

2、@property广泛应用于类的定义中,可以让调用者写出简短的代码。

同时保证对参数进行必要的检查,从而序运行中出错的可能性。

实例

classStudent(object):

@property
defscore(self):
returnself._score

@score.setter
defscore(self,value):
ifnotisinstance(value,int):
raiseValueError('scoremustbeaninteger!')
ifvalue<0orvalue>100:
raiseValueError('scoremustbetween0~100!')
self._score=value

以上就是python中@property的介绍,希望对大家有所帮助。

本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。

THE END

发表回复