python函数property例解

原创
2013/05/08 16:11
阅读数 8.1K

函数property的基本功能就是把类中的方法当作属性来访问,下面以一个有意思的例子介绍一下:

假如有一只猫,它忘了它喜欢吃什么,下面看看我们如何治好它吧   

原代码:    #运行环境 python2.6.5

class Cat(object):
    def __init__(self,food):
        self.food=food

    def eat(self):
        return self.food

    def say(self):
        if 'im_func' in dir(self.eat):
            print "I forgot what to eat,Mybe %s" % self.food
        else:
            print "Miao...,I want to eat fish!"

if __name__ == "__main__":
    tim=Cat('Stone')
    tim.say()

运行后,这只猫说“I forgot what to eat,Mybe Stone”

看来是真有问题了

来个小改动吧:

class Cat(object):
    def __init__(self,food):
        self.food=food

    @property
    def eat(self):
        return self.food

    def say(self):
        if 'im_func' in dir(self.eat):
            print "I forgot what to eat,Mybe %s" % self.food
        else:
            print "Miao...,I want to eat fish!"

if __name__ == "__main__":
    tim=Cat('Stone')
    tim.say()
这回这只猫记起来了

“Miao...,I want to eat fish!”

看来情况出在@property这个装饰器上

假如我们把@property去掉

在后边加一行代码

#!/usr/bin/python
#-*-utf-8-*-
class Cat(object):
    def __init__(self,food):
        self.food=food
    @property
    def eat(self):
        return self.food


    def say(self):
        if 'im_func' in dir(self.eat):
            print "I forgot what to eat,Mybe %s" % self.food
        else:
            print "Miao...,I want to eat fish!"


if __name__ == "__main__":
    tim=Cat('Stone')
    tim.say()
    try:
        tim.eat="Is fish deliciout?"
        print tim.eat
    except:
        print "^^,Fish is so nice"

 
 
 
 

  
  
  

输出:

I forgot what to eat,Mybe Stone
Is fish deliciout?


现在我们把装饰器@property加上去

输出:

Miao...,I want to eat fish!
^^,Fish is so nice


可能这个例子也不是很适合解释这个例子,不过应该还是蛮生动的吧

从网上了解到,用@property装饰成的属性在2.6无法赋值

为了过渡期的兼容性,需要我们自己来配置setter

#!/usr/bin/python
#-*-utf-8-*-
class C(object):
    def __init__(self,x):
        self.__x=x

    @property
    def foo(self):
        return self.__x

    @foo.setter
    def foo(self,value):
        self.__x=value

    @foo.deleter
    def foo(self):
        del self.__x

if __name__ == "__main__":
    c=C(10)
    print c.foo
    c.foo=12
    print c.foo
输出

10

12



展开阅读全文
加载中
点击加入讨论🔥(1) 发布并加入讨论🔥
1 评论
8 收藏
0
分享
返回顶部
顶部