分享

python函数property例解

 sven_ 2015-01-20

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

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

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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”

看来是真有问题了

来个小改动吧:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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去掉

在后边加一行代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#!/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"
  
  
  
  
 <div>
  
  
  
  
 </div>

输出:

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#!/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



    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多