網站首頁 編程語言 正文
Python中私有屬性是前面加兩道下劃線,然后在訪問時就會報“object has no attribute 。。?!?。事實上Python的這種私有屬性只是一種規范,其實通過“_類名__屬性名”還是可以讀寫的,如下。
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,考慮一個需求:我們需要定義一個只讀屬性。寫個getter方法可以實現,但如果想用訪問屬性的方式去讀呢?這就可以用@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)#可讀不可寫
另外需要注意的一點是:@property修飾的方法名和被包裝的屬性不能同名。
@age.setter可以以直接訪問屬性的方式修改屬性,同時可以在修改時加入一些邏輯。
@age.setter
def age(self, age):
if age < 0:
raise Exception("age must be positive")
self.__age = age
至于Python中的@property、@xxx.setter相比getter、setter有什么優點,我想就是@property、@xxx.setter形式上不需要調用方法,直接通過屬性來訪問吧。
原文鏈接:https://blog.csdn.net/qq_42841873/article/details/125716625
相關推薦
- 2022-11-09 CSS元素定位
- 2022-04-09 SpringBoot 提示:RequestRejectedException:The request
- 2022-08-06 python?sns.countplot()?繪畫條形圖詳情_python
- 2022-11-11 Go?time包AddDate使用解惑實例詳解_Golang
- 2022-11-10 Android開發實現日期時間控件選擇_Android
- 2022-05-04 python工具dtreeviz決策樹可視化和模型可解釋性_python
- 2022-05-28 C#調用WebService的方法介紹_C#教程
- 2022-11-21 在react中使用windicss的問題_React
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支