打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
python函数property例解

 函数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



本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
python 面向对象全面详解
继承
【Python之路】特别篇
python基础(25):面向对象三大特性二(多态、封装)
一个代码告诉你self、初始化、继承
错题总结
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服