@property和@setter和@getter
生活随笔
收集整理的這篇文章主要介紹了
@property和@setter和@getter
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
以下四種情況:
只讀不可寫
可寫可讀
不可寫不可讀(那你就沒(méi)必要自己把這個(gè)成員變量封裝到類里面了吧)
可寫不可讀(不存在)
所以常見情況其實(shí)只有兩種.
?
?
| @property | @xxx.getter | @xxx.setter | 可寫 | 可讀 | 代碼 | 備注 |
| O | X | O | O | O | hello1.py | ? |
| O | X | X | X | O | hello2.py | ? |
@property具備@xxx.setter效果,產(chǎn)生可讀效果.
這三個(gè)裝飾器件的效果是:
可讀不一定可寫
可寫的一定可讀
#--------------------------------------附錄---------------------------------------------------------------
hello1.py
class Rectangle(object):# 服務(wù)于返回?cái)?shù)值@propertydef width(self):# 變量名不與方法名重復(fù),改為true_width,下同print("@property called")return self.true_width# 服務(wù)于設(shè)數(shù)值@width.setterdef width(self, input_width):print("setter method called")print("input_width=",input_width)self.true_width = input_width #-----------------------------------------------------------------@propertydef height(self):return self.true_height@height.setter#與property定義的方法名要一致def height(self, input_height):self.true_height = input_height #----------------------------------------------------------------- s = Rectangle() # 與方法名一致 s.width = 1024 s.height = 768print("*********下面是輸出區(qū)域************") print("s.width=",s.width) print("s.true_width=",s.true_width) print("--------------------") print(s.height)?
hello2.py
class Student(object): # 服務(wù)于返回(可讀)@propertydef birth(self):return self._birth# 服務(wù)于設(shè)數(shù)值(可寫)@birth.setterdef birth(self, value):self._birth = value #-----------------------------------------------------------------# 服務(wù)于返回(可讀)@propertydef age(self):return 2015 - self._birth#-----------------------------------------------------------------s = Student() # 與方法名一致 s.birth = 1024 # s.age = 768#如果執(zhí)行此句會(huì)報(bào)錯(cuò)print("*********下面是輸出區(qū)域************") print("s.birth=",s.birth) print("s.age=",s.age)?
總結(jié)
以上是生活随笔為你收集整理的@property和@setter和@getter的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 目前天津的疫情是“从物到人”——天津疫情
- 下一篇: 天天生鲜的用户登录机制和redis的作用