Python property的理解和使用

2021-09-23 23:54:11 字數 1661 閱讀 4197

重看狗書,看到對user表定義的時候有下面兩行

@property

def password(self):

raise attributeerror('password is not a readable attribute')

@password.setter

def password(self, password):

self.password_hash = generate_password_hash(password)12

3456

7遂重溫下這個property的使用

在我們定義資料庫欄位類的時候,往往需要對其中的類屬性做一些限制,一般用get和set方法來寫,那在python中,我們該怎麼做能夠少寫**,又能優雅的實現想要的限制,減少錯誤的發生呢,這時候就需要我們的@property閃亮登場啦,巴拉巴拉能量……..

用**來舉例子更容易理解,比如乙個學生成績表定義成這樣

class student(object):

def get_score(self):

return self._score

def set_score(self, value):

if not isinstance(value, int):

raise valueerror('score must be an integer!')

if value < 0 or value > 100:

raise valueerror('score must between 0 ~ 100!')

self._score = value12

3456

78910

11我們呼叫的時候需要這麼呼叫:

>>> s = student()

>>> s.set_score(60) # ok!

>>> s.get_score()

60>>> s.set_score(9999)

traceback (most recent call last):

...valueerror: score must between 0 ~ 100!12

3456

78但是為了方便,節省時間,我們不想寫s.set_score(9999)啊,直接寫s.score = 9999不是更快麼,加了方法做限制不能讓呼叫的時候變麻煩啊,@property快來幫忙….

class student(object):

@property

def score(self):

return self._score

@score.setter

def score(self,value):

if not isinstance(value, int):

raise valueerror('分數必須是整數才行吶')

if value < 0 or value > 100:

raise valueerror('分數必須0-100之間')

self._score = value12

3456

78910

1112

13看上面**可知,把get方法變為屬性只需要加上@property裝飾器即可,此時@property本身又會建立另外乙個裝飾器@score.setter,負責把set方法變成給屬性賦值,這麼做完後,我們呼叫起來既可控又方便

python property 私有屬性

加有 變數名 的私有屬性直接訪問不了,用get.和set.方法,提供個介面進行訪問。property的使用 私有屬性,用來簡化訪問私有屬性,提供開放性介面,共外界訪問 class student def init self,name,age self.name name self.age age d...

python property 的詳細使用方法

property 有兩種使用方式裝飾器方式 官方幫助文件 property fget none,fset none,fdel none,doc none property attribute decorators make defining new properties or modifying e...

python property 的理解以及它的坑

1 property就是既擁有set get方法的靈活性,又具有屬性直接賦值取值的簡便性 2 property的屬性名必須有下劃線,不然會報錯 3 在乙個方法前加上 property之後,你的方法就會自動擁有 get 直接取值的能力,以及可賦值的屬性 硬要理解的話,下面兩段 效果是一樣的 prope...