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 setx(self, value): self._x = value def delx(self): del self._x x = property(getx, setx, delx, "I'm the 'x' property.")
a = C() print C.x.__doc__ #打印doc print a.x #调用a.getx() a.x = 100 #调用a.setx() print a.x try: del a.x #调用a.delx() print a.x #已被删除,报错 except Exception, e: print e
输出结果:
I'm the 'x' property.
None 100 'C' object has no attribute '_x'
2.利用property装饰器,让成员函数称为只读的
class Parrot(object): def __init__(self): self._voltage = 100000 @property def voltage(self): """Get the current voltage.""" return self._voltage a = Parrot() print a.voltage #通过属性调用voltage函数 try: print a.voltage() #不允许调用函数,为只读的 except Exception as e: print e
输出结果:
100000 'int' object is not callable
3.利用property装饰器实现property函数的功能
class C(object): def __init__(self): self._x = None @property def x(self): """I'm the 'x' property.""" return self._x @x.setter def x(self, value): self._x = value @x.deleter def x(self): del self._x
其他应用
1.bottle源码中的应用
class Request(threading.local): """ Represents a single request using thread-local namespace. """ ... @property def method(self): ''' Returns the request method (GET,POST,PUT,DELETE,...) ''' return self._environ.get('REQUEST_METHOD', 'GET').upper() @property def query_string(self): ''' Content of QUERY_STRING ''' return self._environ.get('QUERY_STRING', '') @property def input_length(self): ''' Content of CONTENT_LENGTH ''' try: return int(self._environ.get('CONTENT_LENGTH', '0')) except ValueError: return 0 @property def COOKIES(self): """Returns a dict with COOKIES.""" if self._COOKIES is None: raw_dict = Cookie.SimpleCookie(self._environ.get('HTTP_COOKIE','')) self._COOKIES = {} for cookie in raw_dict.values(): self._COOKIES[cookie.key] = cookie.value return self._COOKIES
2.在django model中的应用,实现连表查询
from django.db import models class Person(models.Model): name = models.CharField(max_length=30) tel = models.CharField(max_length=30) class Score(models.Model): pid = models.IntegerField() score = models.IntegerField() def get_person_name(): return Person.objects.get(id=pid) name = property(get_person_name) #name称为Score表的属性,通过与Person表联合查询获取name
本文 由 cococo点点 创作,采用 知识共享 署名-非商业性使用-相同方式共享 3.0 中国大陆 许可协议进行许可。欢迎转载,请注明出处:
转载自:cococo点点 http://www.cnblogs.com/coder2012
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· .NET周刊【3月第1期 2025-03-02】
· [AI/GPT/综述] AI Agent的设计模式综述
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!