python中对实例属性的操作可以自定义方法如get() set() ,调用的时候使用instance.get() instance.set("××"),这两个方法也叫访问器和设置器,这样也可以在自定义的方法中设置属性的过滤条件,但是这样调用起来很不方便,而如果使用instance.x instance.x="××"直接调用虽然方便,但是不安全,也无法设置属性赋值的时候的过滤条件,要想可以方便访问和设置,又能在赋值的时候设置条件,可以使用
1 描述符
2 property
class Attr(object):
def __init__(self, name, type_):
self.name = name
self.type_ = type_
def __get__(self, instance, cls):
return instance.__dict__[self.name]
def __set__(self, instance, value):
if not isinstance(value, self.type_):
raise TypeError('expected an %s' % self.type_)
instance.__dict__[self.name] = value
def __delete__(self, instance):
raise AttributeError("can't delete this attr")
class Person(object):
name = Attr('name', str)
age = Attr('age', int)
height = Attr('height', float)
def getweight(self):
return self.weight
def setweight(self,weight):
if not isinstance(weight,(int,float)):
raise ValueError("wrong type")
self.weight=weight
w=property(getweight,setweight)
s = Person()
s.name = 'Bob'
s.age = 17
s.height = 1.82
print(s.name,s.age,s.height)
s.w="a"
print(s.w)
结果:
Bob 17 1.82
Traceback (most recent call last):
File "C:/Users/xsy/AppData/Local/Programs/Python/Python36/444.py", line 36, in <module>
s.w="a"
File "C:/Users/xsy/AppData/Local/Programs/Python/Python36/444.py", line 26, in setweight
raise ValueError("wrong type")
ValueError: wrong type
>>>