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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM