python2.7
代码为:
class Integer:
def __init__(self,name):
self.name=name
def __get__(self,instance,cls):
if instance is None:
return self
else:
return instance.__dict__[self.name]
def __set__(self,instance,value):
if not isinstance(value,int):
raise TypeError('Expected an int')
instance.__dict__[self.name]=value
def __delete__(self,instance):
del instance.__dict__[self.name]
class Point:
x=Integer('x')
y=Integer('y')
def __init__(self,x,y):
self.x=x
self.y=y
if __name__=="__main__":
p=Point(2,3)
print p.x
p.y=2.3
print p.y
输出结果为:
2
2.3
可以看到p.y居然可以为小数。也就是说description不起作用。。
原因:
把类的声明从class Integer改为class Integer(object),其他的类定义都是类似:
最终代码为:
__author__ = 'Administrator'
class Integer(object):
def __init__(self,name):
self.name=name
def __get__(self,instance,cls):
if instance is None:
return self
else:
return instance.__dict__[self.name]
def __set__(self,instance,value):
if not isinstance(value,int):
raise TypeError('Expected an int')
instance.__dict__[self.name]=value
def __delete__(self,instance):
del instance.__dict__[self.name]
class Point(object):
x=Integer('x')
y=Integer('y')
def __init__(self,x,y):
self.x=x
self.y=y
if __name__=="__main__":
p=Point(2,3)
print p.x
p.y=2.3
print p.y
最终结果为:
2
Traceback (most recent call last):
File "G:/pycode/SimpleCode/PY_CookBook/chapter8/one.py", line 31, in <module>
p.y=2.3
File "G:/pycode/SimpleCode/PY_CookBook/chapter8/one.py", line 14, in __set__
raise TypeError('Expected an int')
TypeError: Expected an int