Python-属性(property)
生活随笔
收集整理的這篇文章主要介紹了
Python-属性(property)
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
在2.6版本中,添加了一種新的類成員函數(shù)的訪問(wèn)方式--property。
原型
class property([fget[, fset[, fdel[, doc]]]])fget:獲取屬性
fset:設(shè)置屬性
fdel:刪除屬性
doc:屬性含義
用法
1.讓成員函數(shù)通過(guò)屬性方式調(diào)用
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 #調(diào)用a.getx() a.x = 100 #調(diào)用a.setx() print a.x try: del a.x #調(diào)用a.delx() print a.x #已被刪除,報(bào)錯(cuò) except Exception, e: print e輸出結(jié)果:
I'm the 'x' property.None 100 'C' object has no attribute '_x'
2.利用property裝飾器,讓成員函數(shù)稱為只讀的
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 #通過(guò)屬性調(diào)用voltage函數(shù) try: print a.voltage() #不允許調(diào)用函數(shù),為只讀的 except Exception as e: print e輸出結(jié)果:
100000 'int' object is not callable3.利用property裝飾器實(shí)現(xiàn)property函數(shù)的功能
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其他應(yīng)用
1.bottle源碼中的應(yīng)用
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._COOKIES2.在django model中的應(yīng)用,實(shí)現(xiàn)連表查詢
from django.db import modelsclass 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表的屬性,通過(guò)與Person表聯(lián)合查詢獲取name轉(zhuǎn)載于:https://www.cnblogs.com/JohnABC/p/5685699.html
總結(jié)
以上是生活随笔為你收集整理的Python-属性(property)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: CYQ.Data V5 从入门到放弃OR
- 下一篇: 【MongoDB】增删改查基本操作