對python中property函式的理解

2021-04-15 11:23:28 字數 1868 閱讀 3111

對python中property函式的理解

class

status(object):

def__init__

(self,

created_at

=none,

id=none,

text

=none,

user

=none,

now=none):

self.created_at 

=created_at

self.id =id

self.text 

=text

self.user 

=user

self.now 

=now

defgetcreatedat(self):

return

self._created_at

defsetcreatedat(self, created_at):

self._created_at 

=created_at

created_at 

=property(getcreatedat, setcreatedat,

doc='

the time this status message was posted.')

其中,對於類成員created_at就使用了property函式,翻看了python 2.5 document裡面對於property函式的解釋:

2.1 built-in functions

property( [fget[, fset[, fdel[, doc]]]])

return a property attribute for new-style classes (classes that derive from object).

fget is a function for getting an attribute value, likewise fset is a function for setting, and fdel a function for del'ing, an attribute. typical use is to define a managed attribute x:

class

c(object):

def__init__

(self): self._x 

=none

defgetx(self): 

return

self._x

defsetx(self, value): self._x 

=value

defdelx(self): 

delself._x

x =property(getx, setx, delx, 

"i'm the 'x' property.")

if given, doc will be the docstring of the property attribute. otherwise, the property will copy fget's docstring (if it exists). this makes it possible to create read-only properties easily using property() as a decorator:

大概含義是,如果要使用property函式,首先定義class的時候必須是object的子類。通過property的定義,當獲取成員x的值時,就會呼叫getx函式,當給成員x賦值時,就會呼叫setx函式,當刪除x時,就會呼叫delx函式。使用屬性的好處就是因為在呼叫函式,可以做一些檢查。如果沒有嚴格的要求,直接使用例項屬性可能更方便。

同時,還可以通過指定doc的值來為類成員定義docstring。 

JS中Attribute和property的區別

在使用angular中的資料繫結時,發現對html屬性和dom屬性不是很清楚,順便屢屢清楚這二者的區別。attribute html屬性,書寫在標籤內的屬性,使用setattribute 和getattribute 進行設定和獲取。property dom屬性,html標籤對應的dom節點屬性,使用...

Python 今天抽空學習了 Property

1 property使方法像屬性一樣呼叫 property可以把乙個例項方法變成其同名屬性,以支援.號訪問,它亦可標記設定限制,加以規範 2 property成為屬性函式,可以對屬性賦值時做必要的檢查,比如在setter方法裡加過濾判斷條件。3 顯得相對簡潔一些,相比自定義的get和set方法,pr...

python中物件包含 Python中的物件

python中的物件 在python中,一切都是物件。為了證明,你可以開啟乙個repl並探索使用isinstance true isinstance list object true isinstance true,object true def foo pass isinstance foo,ob...