python2 description不起作用

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



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值