本文以廖雪峰的官方网站为参考来学习python的。其学习链接为廖雪峰小白学python教程。
本文是学习到python的实例属性和类属性。参考链接廖雪峰python使用@property。
class Student(object):
def get_score(self):
return self._score
def set_score(self,value):
if not isinstance(value,int):
raise ValueError('score must be an integer!')
if value < 0 or value > 100:
raise ValueError('score must between 0 ~ 100!')
self._score = value
s = Student()
s.set_score(60)
print(s.get_score())
运行结果: 60
如果接上代码
s.set_score(9999)
则会报错:
Traceback (most recent call last):
File "**********", line **, in <module>
s.set_score(9999)
File "***********", line **, in set_score
raise ValueError('score must between 0 ~ 100!')
ValueError: score must between 0 ~ 100!
class Student(object):
@property
def score(self):
return self._score
@score.setter
def score(self,value):
if not isinstance(value, int):
raise ValueError('score must be an integer!')
if value < 0 or value > 100:
raise ValueError(' score must between 0 ~ 100!')
self._score = value
s = Student()
s.score = 60
print(s.score)
运行结果:60
加上代码,
s.score = 9000
就会报错:
Traceback (most recent call last):
File "***********", line **, in <module>
s.score = 9000
File "***********", line **, in score
raise ValueError(' score must between 0 ~ 100!')
ValueError: score must between 0 ~ 100!
笔记:
@property 把一个getter方法变成属性。又创建了另一个装饰器@score.setter,负责把一个setter方法变成属性赋值。于是,我们就有了一个可控属性操作。
还可以定义只读属性,只定义getter方法,不定义setter方法就是一个只读属性:
class Student(object):
@property
def birth(self):
return self._birth
@birth.setter
def birth(self,value):
self._birth = value
@property
def age(self):
return 2015-self._birth
s = Student()
s.birth = 2000
print(s.birth)
print(s.age)
运行结果:
2000
15
练习:
# -*- coding: utf-8 -*-
class Screen(object):
@property
def width(self):
return self._width
@width.setter
def width(self,value):
self._width = value
@property
def height(self):
return self._height
@width.setter
def height(self,value):
self._height = value
@property
def resolution(self):
return self._width * self._height
运行结果:
resolution = 786432
测试通过!