python property的介紹與使用

2022-10-09 04:27:12 字數 1849 閱讀 3988

python的@property是python的一種裝飾器,是用來修飾方法的。

我們可以使用@property裝飾器來建立唯讀屬性,@property裝飾器會將方法轉換為相同名稱的唯讀屬性,可以與所定義的屬性配合使用,這樣可以防止屬性被修改。

class dataset(object):

@property

def method_with_property(self): ##含有@property

return 15

def method_without_property(self): ##不含@property

return 15

l = dataset()

print(l.method_with_property) # 加了@property後,可以用呼叫屬性的形式來呼叫方法,後面不需要加()。

print(l.method_without_property()) #沒有加@property , 必須使用正常的呼叫方法的形式,即在後面加()

兩個都輸出為15。

class dataset(object):

@property

def method_with_property(self): ##含有@property

return 15

l = dataset()

print(l.method_with_property()) # 加了@property後,可以用呼叫屬性的形式來呼叫方法,後面不需要加()。

如果使用property進行修飾後,又在呼叫的時候,方法後面新增了(), 那麼就會顯示錯誤資訊:typeerror: 'int' object is not callable,也就是說新增@property 後,這個方法就變成了乙個屬性,如果後面加入了(),那麼就是當作函式來呼叫,而它卻不是callable(可呼叫)的。

class dataset(object):

def method_without_property(self): ##不含@property

return 15

l = dataset()

print(l.method_without_property) #沒有加@property , 必須使用正常的呼叫方法的形式,即在後面加()

沒有使用property修飾,它是一種方法,如果把括號去掉,不會報錯輸出的就會是方法存放的位址。

​ 由於python進行屬性的定義時,沒辦法設定私有屬性,因此要通過@property的方法來進行設定。這樣可以隱藏屬性名,讓使用者進行使用的時候無法隨意修改。

class dataset(object):

def __init__(self):

self._images = 1

self._labels = 2 #定義屬性的名稱

@property

def images(self): #方法加入@property後,這個方法相當於乙個屬性,這個屬性可以讓使用者進行使用,而且使用者有沒辦法隨意修改。

return self._images

@property

def labels(self):

return self._labels

l = dataset()

#使用者進行屬性呼叫的時候,直接呼叫images即可,而不用知道屬性名_images,因此使用者無法更改屬性,從而保護了類的屬性。

print(l.images) # 加了@property後,可以用呼叫屬性的形式來呼叫方法,後面不需要加()。

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的理解和使用

重看狗書,看到對user表定義的時候有下面兩行 property def password self raise attributeerror password is not a readable attribute password.setter def password self,passwor...