python学习-property
·
#!/usr/bin/env python
#-*- coding:utf-8 -*-
'@property'
__author__ = 'hui.qian'
class Student(object):
pass
s = Student()
s.age = 1000
print s.age
'''
在实际过程中,年龄肯定不会大于1000岁
这说明一个问题,属性的设置要有判断检查,
不能随便定义,所以一般定义属性都是用
set\get方法
'''
class Student(object):
def set_age(self,age):
if age > 150:
raise ValueError('Shemale!')
elif age<0:
raise ValueError('The noise?')
self.age = age
def get_age(self):
return self.age
s1 = Student()
#s1.set_age(-1)
#s1.set_age(151)
s1.set_age(100)
print s1.get_age()
'''
但是有人就想要用s1.age的方式调用(反正不是我)
那就要请@property出场啦
'''
class Student1(object):
@property
def age(self):
return self._age
@age.setter
def age(self,value):
if value > 150:
raise ValueError('Shemale!')
elif value<0:
raise ValueError('The noise?')
else:
self._age = value
'上面的@property一定要先定义,不然不识别age'
s2 = Student1()
s2.age = 99
print s2.age
#如果没有setter的话,该属性就变为只读属性
更多推荐



所有评论(0)