Python学习10:@perporty
Posted CQ小子
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python学习10:@perporty相关的知识,希望对你有一定的参考价值。
本文学习Python的笔记,仅供参考
一般情况下在面向对象的编程中,属性不暴露在外面,而是通过一个接口函数去设置,比如下面的例子,定义了一个student的类,里面有两个私有的成员变量name和score,同时也有4个方法,print_name,set_name,set_socre,get_score。
class Student(object):
def __init__(self,name,score):
self.__name = name
self.__score = score
def print_name(self):
print(self.__name)
def set_name(self,name):
self.__name = name
def set_score(self,score):
self.__score = score
def get_score(self):
return self.__score
bat = Student("zhangsan",99)
bat.print_name()
bat.set_name("lisi")
bat.print_name()
bat.set_score(88)
print(bat.get_score())
这四个成员函数分别用来获取和设置成员变量,从调用的状况来看,我设置name为lisi,成绩为88,执行结果为:
======================== RESTART: E:/python/class.py ========================
zhangsan
lisi
88
函数中没有进行参数检查,可以把参数检查的部分加上:
class Student(object):
def __init__(self,name,score):
self.__name = name
self.__score = score
def print_name(self):
print(self.__name)
def set_name(self,name):
if not isinstance(name,str):
raise ValueError("name must be an str")
self.__name = name
def set_score(self,score):
if not isinstance(score,int):
raise ValueError("score must be an int")
if score < 0 or score > 100:
raise ValueError("Score must between 0~100")
self.__score = score
def get_score(self):
return self.__score
运行下设置score,产生了如期的错误
>>> bat.set_score(999)
Traceback (most recent call last):
File "<pyshell#40>", line 1, in <module>
bat.set_score(999)
File "<pyshell#34>", line 15, in set_score
raise ValueError("Score must between 0~100")
ValueError: Score must between 0~100
有没有既能检查参数,又可以用类似属性这样简单的方式来访问类的变量呢?对于追求完美的Python程序员来说,这是必须要做到的!
Python内置的
@property
装饰器就是负责把一个方法变成属性调用的:
@property可以把一个getter方法变成属性,同时又生成一个@score.setter把setter方法变成属性
class Student(object):
def print_name(self):
print(self.__name)
def set_name(self,name):
if not isinstance(name,str):
raise ValueError("name must be an str")
self.__name = name
@property
def score(self):
return self.__score
@score.setter
def score(self,score):
if not isinstance(score,int):
raise ValueError("score must be an int")
if score < 0 or score > 100:
raise ValueError("Score must between 0~100")
self.__score = score
实验下结果:
>>> bat.set_name("zhangsan")
>>> bat.score = 99
>>> bat.score
99
>>> bat.score = 1000
Traceback (most recent call last):
File "<pyshell#47>", line 1, in <module>
bat.score = 1000
File "<pyshell#41>", line 16, in score
raise ValueError("Score must between 0~100")
ValueError: Score must between 0~100
既能够参数检查,有能够像调用属性那样实际上去调用成员函数
以上是关于Python学习10:@perporty的主要内容,如果未能解决你的问题,请参考以下文章