網(wǎng)站首頁 編程語言 正文
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
相關(guān)推薦
- 2022-07-11 deepstream 問題
- 2022-07-04 C#使用System.Buffer以字節(jié)數(shù)組Byte[]操作基元類型數(shù)據(jù)_C#教程
- 2022-03-27 python內(nèi)置函數(shù)之eval函數(shù)詳解_python
- 2022-02-20 千分位保留兩位小數(shù),出現(xiàn)“toFixed() is not a function”的解決辦法
- 2022-11-24 redis使用skiplist跳表的原因解析_Redis
- 2022-09-24 python實(shí)現(xiàn)字母閃爍效果的示例代碼_python
- 2023-07-04 spring之BeanDefinition
- 2023-10-17 react跨域請(qǐng)求數(shù)據(jù)(proxy)
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細(xì)win安裝深度學(xué)習(xí)環(huán)境2025年最新版(
- Linux 中運(yùn)行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲(chǔ)小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎(chǔ)操作-- 運(yùn)算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認(rèn)證信息的處理
- Spring Security之認(rèn)證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權(quán)
- redisson分布式鎖中waittime的設(shè)
- maven:解決release錯(cuò)誤:Artif
- restTemplate使用總結(jié)
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實(shí)現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務(wù)發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結(jié)構(gòu)-簡(jiǎn)單動(dòng)態(tài)字符串(SD
- arthas操作spring被代理目標(biāo)對(duì)象命令
- Spring中的單例模式應(yīng)用詳解
- 聊聊消息隊(duì)列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠(yuǎn)程分支