YO~~ 剛跨入AI人工智慧領域的小小工程師, 熱愛自學, 熱愛分享, 下班後的我想為自己Coding, 積極撰寫教學文, 想將自學的程式知識分享給大家, 不斷追求進步的自己, 希望有一天能回饋社會,幫助需要幫助的人, 如果您有什麼很酷的想法,也覺得我還行,歡迎您找我合作~~ IG: https://www.instagram.com/coding_4_me/
Coding起來-Python設計-@Property用法
1. 基本用法:
首先我們先來看看property很基本的用法,過去我們可能要在function裡print,它才會自動轉成我們要的文字,而return總是return一些不是我們要的而且我們也看不懂,那這邊就來看看加上@property與沒加的區別,會很清楚發現:
a. 如果不加 @property print 會得到:
<bound method house.full_information of <__main__.house object at 0x000001a8b051e988>></bound>
b. 如果加上@property print 會得到 :
##這是過去我們用print的方法: address:any Town any Street, name:Turtle, phone_number:09xx
## new method: address:any Town any Street, name:Turtle, phone_number:09xx
## property 基本用法 (有無property的區別) class House: def __init__(self, address, name, phone_number): self.address = address self.name = name self.phone_number = phone_number @property def full_information(self): print("這是過去我們用print的方法: address:%s, name:%s, phone_number:%s" %(self.address, self.name, self.phone_number)) return "new method: address:%s, name:%s, phone_number:%s" %(self.address, self.name, self.phone_number) little_turtle_home = House('any Town any Street', 'Turtle', '09xx') print(little_turtle_home.full_information) ## 如果不加 @property print 會得到 <bound method House.full_information of <__main__.House object at 0x000001A8B051E988>> ## 如果加上@property print 會得到 ## 這是過去我們用print的方法: address:any Town any Street, name:Turtle, phone_number:09xx ##new method: address:any Town any Street, name:Turtle, phone_number:09xx little_turtle_home.full_information = "address:any county, name:Fish, phone_number:06xx" ## AttributeError: can't set attribute
2. 特性:
a. 用法一: property其實就是把class 底下這個function當attribute(屬性),什麼意思呢? 它會把這個function轉成只能讀的特性,我們可以讀取 little_turtle_home.full_information,卻不能賦值給它,如果硬要賦值的話程式會報錯(AttributeError: can't set attribute)
little_turtle_home.full_information = "address:any county, name:Fish, phone_number:06xx" ## AttributeError: can't set attribute
b. 用法二: property 如何賦值? 其實就是怎麼實現 getter 、 setter 與deleter 的用法
property 如何使用 getter 、 setter and deleter,很特別只要在我們要使用的function上面加上@(function name).setter 與 @(function name).deleter 就可以囉,那getter怎麼辦?,don’t worry 它就是加上@property那個了
舉例:
介紹了@property兩種用法,它把class原本只能讀取寫死的感覺,改變成可以隨時賦予新值,這樣會讓我們在使用上彈性非常多,希望大家都有收穫!! 1. 單純的讀取方法 2. getter, setter and deleter的實現
class House: def __init__(self, name): self.name = name @property def full_name(self): return self.name @full_name.setter def full_name(self, value): self.name = value @full_name.deleter def full_name(self): del self.name print('have a nice day') little_turtle_home = House('Turtle') print(little_turtle_home.full_name) ## Turtle little_turtle_home.full_name = 'Fish' print(little_turtle_home.full_name) ## Fish del little_turtle_home.full_name ## have a nice day little_turtle_home.full_name = 'Star' print(little_turtle_home.full_name) ## Star
Reference:
https://chenhh.gitbooks.io/parallel_processing/cython/python_class.html
https://www.maxlist.xyz/2019/12/25/python-property/
喜欢我的文章吗?
别忘了给点支持与赞赏,让我知道创作的路上有你陪伴。
发布评论…