python property内建函数的介绍

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

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

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

?


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

classCat(object):

def__init__(self,food):

self.food=food

defeat(self):

returnself.food

defsay(self):

if‘im_func‘indir(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

classCat(object):

def__init__(self,food):

self.food=food

@property

defeat(self):

returnself.food

defsay(self):

if‘im_func‘indir(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-*-

classCat(object):

def__init__(self,food):

self.food=food

@property

defeat(self):

returnself.food

defsay(self):

if‘im_func‘indir(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?"

printtim.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修饰的方法就变成了数据属性了,不再是方法了,如下:

class Cat(object):
    def __init__(self,food):
        self.food =  food
    #@property
    def eat(self):
        return self.food
    def say(self):
        print dir(self.eat)
        if ‘im_func‘ in dir(self.eat):
            print "i forgot what to eat,maybe %s"%self.food
        else:
            print "meow..., I want to eat fish!"

if __name__ ==‘__main__‘:
    tim = Cat(‘stone‘)
    tim.say()
    try:
        tim.eat = "Is fish delicious?"
        print tim.eat
    except:
        print ‘^^,fish is so nice!‘

运行结果是:

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

如果是以下代码:

class Cat(object):
    def __init__(self,food):
        self.food =  food
    #@property
    def eat(self):
        return self.food
    def say(self):
        print dir(self.eat)
        if ‘im_func‘ in dir(self.eat):
            print "i forgot what to eat,maybe %s"%self.food
        else:
            print "meow..., I want to eat fish!"

if __name__ ==‘__main__‘:
    tim = Cat(‘stone‘)
    tim.say()
    try:
        tim.eat = "Is fish delicious?"
        print tim.eat
    except:
        print ‘^^,fish is so nice!‘

运行结果是:

i forgot what to eat,maybe stone
Is fish delicious?

如果是以下代码:

class Cat(object):
    def __init__(self,food):
        self.food =  food
    @property
    def eat(self):
        return self.food
    def say(self):
        print dir(self.eat)
        if ‘im_func‘ in dir(self.eat):
            print "i forgot what to eat,maybe %s"%self.food
        else:
            print "meow..., I want to eat fish!"

if __name__ ==‘__main__‘:
    tim = Cat(‘stone‘)
    tim.say()
    try:
        tim.eat1 = "Is fish delicious?"
        print tim.eat1
    except:
        print ‘^^,fish is so nice!‘

运行结果是:

meow..., I want to eat fish!
Is fish delicious?

在这里虽然tim.eat已经不再是方法了,而是数据属性了,但是由于我们在主函数里面没有修改tim.eat 而是修改了tim.eat1,所以得到的结果是上面的结果,呵呵

最主要的就是经过property修饰后函数不再是函数,方法不再是方法,而是数据属性了,

时间: 2024-08-25 00:19:02

python property内建函数的介绍的相关文章

python property

python property 在2.6版本中,添加了一种新的类成员函数的访问方式--property. 原型 class property([fget[, fset[, fdel[, doc]]]]) fget:获取属性 fset:设置属性 fdel:删除属性 doc:属性含义 用法 1.让成员函数通过属性方式调用 class C(object): def __init__(self): self._x = None def getx(self): return self._x def set

Python学习笔记-模块介绍(三)-模块包和搜索路径

一个python文件就是一个模块,使用独立的命名空间,但实际使用过程中单单用模块来定义python功能显然还不够.因为一个大型的系统几千上万个模块是很正常的事情,如果都聚集在一起显然不好管理并且有命名冲突的可能,因此python中也出现了一个包的概念. 一.python中的包介绍 包是通过使用"点模块名称"创建Python模块命名空间的一种方法.列如,模块名称 A.B 表示一个在名为 A的包下的名为B的子模块.就像使用模块让不同模块的作者无需担心彼此全局变量名称(冲突)一样,点模块名称

python字符串内建函数总结

python的字符串常用内建函数        方法                        描述 string.capitalize() 将字符串的第一个字母大写 string.center(width) 返回一个原字符串居中,并使用空格填充至长度 width 的新字符串 string.count(str, beg=0, end=len(string)) 返回 str 在 string 里面出现的次数,如果 beg 或者 end 指定则返回指定范围内 str 出现的次数 string.e

Python:内建函数总结

前言:Python的内建函数为编程提供了很大的方便,为方便以后的学习,在这里对Python 3.x的内建函数做一个相对完整的总结 A ? abs(x):如果x是复数,则返回它的大小:若是整数或浮点数则返回它的绝对值 1 print(abs(-1)) 2 print(abs(-10.01)) 3 print(abs(3+4j)) #返回复数的大小 ? all(iterable):如果iterable所有的元素不为0.''.False或者iterable为空,all(iterable)返回True,

python 解释器内建函数

python解释器内建函数列表如下: 001.abs() 求绝对值 #!/usr/bin/python if __name__=="__main__": print(abs(-100))#打印100 002.all() 如果参数列表中所有的值都是True,all函数才返回True #!/usr/bin/python if __name__=="__main__": conditions=[True,False] print(all(conditions))#打印Fa

python学习手册——1介绍python对象类型

在python ,数据以对象的形式出现--无论是python提供的内置对象,还是使用python或是像C扩展库这样的扩展语言工具创建的对象.尽管在以后才能确定这一概念,但对象无非是内在中的一部分,包含数值和相关操作的集合. 由于对象是python 最基本的概念,从这一章开始我们将会全面地体验python的内置对象类型. python程序可以分解成模块,语句,表达式以及对象,如下所示: 1.程序由模块构成 2.模块包含语句 3.语句包含表达式 4.表达式建立并处理对象 为什么使用内置类型 1.内置

python爬虫实例详细介绍之爬取大众点评的数据

python 爬虫实例详细介绍之爬取大众点评的数据 一. Python作为一种语法简洁.面向对象的解释性语言,其便捷性.容易上手性受到众多程序员的青睐,基于python的包也越来越多,使得python能够帮助我们实现越来越多的功能.本文主要介绍如何利用python进行网站数据的抓取工作.我看到过利用c++和Java进行爬虫的代码,c++的代码很复杂,而且可读性.可理解性较低,不易上手,一般是那些高手用来写着玩加深对c++的理解的,这条路目前对我们不通.Java的可读性还可以,就是代码冗余比较多,

Python @property 属性

Python @property 修饰符 python的property()函数,是内置函数的一个函数, 会返回一个property的属性: 可以在以下网页查看它的描述:property 文档上面说property()作为一个修饰符, 这会创建一个只读的属性. class Parrot: def __init__(self): self._voltage = 100000 @property def voltage(self): """Get the current volt

Python迭代器和生成器介绍

Python迭代器和生成器介绍 迭代器 迭代器是一个实现了迭代器协议的对象,Python中的迭代器协议就是有next方法的对象会前进到下一结果,而在一系列结果的末尾是,则会引发StopIteration. 在for循环中,Python将自动调用工厂函数iter()获得迭代器,自动调用next()获取元素,还完成了检查StopIteration异常的工作. 常用的几个内建数据结构tuple.list.set.dict都支持迭代器,字符串也可以使用迭代操作. 你也可以自己实现一个迭代器,如上所述,只