日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無先后,達(dá)者為師

網(wǎng)站首頁 編程語言 正文

Python的私有屬性及@property

作者:斷云涵雨入孤村 更新時(shí)間: 2022-07-12 編程語言

Python中私有屬性是前面加兩道下劃線,然后在訪問時(shí)就會(huì)報(bào)“object has no attribute 。。?!?。事實(shí)上Python的這種私有屬性只是一種規(guī)范,其實(shí)通過“_類名__屬性名”還是可以讀寫的,如下。

class Dog():

    def __init__(self, age: int):
        self.__age = age
        
dog = Dog(8)
print(dog.__age)#AttributeError: 'Dog' object has no attribute '__age'
print(dog._Dog__age) #8
#寫也是類似的

所以,Python似乎并沒有真正的私有屬性,但我們不妨忘記這種流氓訪問方式。

再說@property,考慮一個(gè)需求:我們需要定義一個(gè)只讀屬性。寫個(gè)getter方法可以實(shí)現(xiàn),但如果想用訪問屬性的方式去讀呢?這就可以用@property,如下。

class Dog():

    def __init__(self, age: int):
        self.__age = age

    @property
    def age(self) -> int: return self.__age
    
dog = Dog(8)
print(dog.age)#可讀不可寫

另外需要注意的一點(diǎn)是:@property修飾的方法名和被包裝的屬性不能同名。
@age.setter可以以直接訪問屬性的方式修改屬性,同時(shí)可以在修改時(shí)加入一些邏輯。

    @age.setter
    def age(self, age):
        if age < 0:
            raise Exception("age must be positive")
        self.__age = age

至于Python中的@property、@xxx.setter相比getter、setter有什么優(yōu)點(diǎn),我想就是@property、@xxx.setter形式上不需要調(diào)用方法,直接通過屬性來訪問吧。

原文鏈接:https://blog.csdn.net/qq_42841873/article/details/125716625

欄目分類
最近更新