YO~~ 剛跨入AI人工智慧領域的小小工程師, 熱愛自學, 熱愛分享, 下班後的我想為自己Coding, 積極撰寫教學文, 想將自學的程式知識分享給大家, 不斷追求進步的自己, 希望有一天能回饋社會,幫助需要幫助的人, 如果您有什麼很酷的想法,也覺得我還行,歡迎您找我合作~~ IG: https://www.instagram.com/coding_4_me/
給自己的Python小筆記: Class 設計(上)
基本的CLASS 設計:
a. self的意義: 就是你宣告的本身 (EX. little_turtle_home = House(‘any Town any Street’, ‘Turtle’, ‘09xx’)),little_turtle_home 就是self, 使我們再執行裡面的函式時,不用寫成House.move_in(little_turtle_home, 2),而只要單純寫成little_turtle_home.move_in(2)就好
b. __del__ 是什麼: __init__是建構子(constructor),而__del__則是deconstructor,只要在程式裡輸入 del little_turtle_home,你就會將你創建出來的object刪除掉, 這樣你就沒辦法使用剛剛創造的object
class House: def __init__(self, address, name, phone_number): self.address = address self.name = name self.phone_number = phone_number self.member = 0 def move_in(self, amount): if amount < 0: raise ValueError("Amazing: people amount can't be negative") else: self.member += amount def move_out(self, amount): if amount > self.member: raise ValueError('exceed the amount of people here') else: self.member -= amount def __del__(self): return "destroy the house" little_turtle_home = House('any Town any Street', 'Turtle', '09xx') little_turtle_home.move_in(2) little_turtle_home.move_in(4) little_turtle_home.move_in(2) little_turtle_home.move_out(2) print(little_turtle_home.member) del little_turtle_home # print(little_turtle_home) ##NameError: name 'little_turtle_home' is not defined
2. __new__ 方法的意義
a.先執行__new__,再執行__init__:
__new__後,會再被__init__初始化,也就是在new裡的變數會被i__init__一樣的變數overwrite(下面的例子: total就被覆寫成init指定的)
b.與__init不同,它必須有return,不然物件不會建立成功
## __new__ 方法 class X(object): def __init__(self,*args,**kargs): print ("init %s" %self.__class__) self.total = 2 def __new__(cls,*args,**kargs): print ("new %s" %cls) cls.total = 4 return object.__new__(cls, *args, **kargs)##如果沒有,使用add會報錯 ## *num 讓我們傳入參數時,可以是tuple def add(cls,*num): for i in num: print(i) print(type(i)) cls.total += i print(cls.total) x = X() ## 先執行new 再執行init(會幫__new__初始化) 再執行add x.add(1,4,8) # output # new <class '__main__.X'> # init <class '__main__.X'> # 1 # <class 'int'> # 4 # <class 'int'> # 8 # <class 'int'> # 15
3. 內建的__dict__ 與 __str__ 用法
a. __dict__: 只要在創建好的object 接著打上.__dict__,就能將數據用dict的方式傳回
b. __str__ : 只要加上這個function,print object的時候會自動幫你啟用__str__ function,轉成str格式印出來
## __dict__ 用法 和 __str__用法 class House: city = "HsinChu" ## class attribute(__dict__ can't load) def __init__(self, address, name, phone_number): self.address = address self.name = name self.phone_number = phone_number self.member = 0 def __str__(self): return ("House name: %s, Address: %s, Phone Number: %s"%(self.name,self.address,self.phone_number)) ## 實際操作 little_turtle_home = House('any Town any Street', 'Turtle', '0999') print(little_turtle_home) ## print type(string) ## same as print(little_turtle_home.__str__()) ## Output # House name: Turtle, Address: any Town any Street, Phone Number: 0999 print(little_turtle_home.__dict__) ##change to dict format ## Out put # {'address': 'any Town any Street', 'name': 'Turtle', 'phone_number': '0999', 'member': 0} print(little_turtle_home.__dict__['address']) # any Town any Street
4. __dict__其他用法
step1: 先建立一個dict,這邊我沿用了上面的例子,產生一個dict ({‘address’: ‘any Town any Street’, ‘name’: ‘Turtle’, ‘phone_number’: ‘09xx’})
step2: 如何將dict, 放入class 並init 成一個一個的變數
method1 : 把dict裡的值一個一個帶入variable
method2: 利用self.__dict__update(),直接自動轉成我們要的格式
## __dict__ 應用 ## create a dict class House: def __init__(self, address, name, phone_number): self.address = address self.name = name self.phone_number = phone_number little_turtle_home = House('any Town any Street', 'Turtle', '09xx') print(little_turtle_home.__dict__) ## Output #{'address': 'any Town any Street', 'name': 'Turtle', 'phone_number': '09xx'} ## if your input is dict format ## method1: class House1: def __init__(self,dict_obj): self.address = dict_obj['address'] self.name = dict_obj['name'] self.phone_number = dict_obj['phone_number'] little_turtle_home1 = House1(little_turtle_home.__dict__) print(little_turtle_home1.name) ## Output #Turtle # method2: you can use self.__dict__.update() : help you easily parse the dict into variable format class House2: def __init__(self,dict_obj): self.__dict__.update(dict_obj) little_turtle_home2 = House1(little_turtle_home.__dict__) print(little_turtle_home2.name) ## Output #Turtle
5.類別屬性與實體屬性
1.簡單來說:
a. 屬性就是.後面都是屬性,像是little_turtle_home.tv_amount
b. 類別屬性: 在class中,不在function底下的屬性
c. 實體屬性: 在class中,在function底下的屬性
2. 當類別屬性與實體屬性所使用的名稱相同, 每次修改就會流動實體屬性一起改
class House: tv_amount = 1 #類別屬性 def __init__(self, tv_amount): tv_amount = 1 #實體屬性 House.tv_amount += 1 little_turtle_home = House(1) print(little_turtle_home.tv_amount) #2 print(House.tv_amount) #2 little_turtle_home1 = House(1) print(little_turtle_home1.tv_amount) #3 print(House.tv_amount) #3
3. 當類別屬性與實體屬性所使用的名稱不同(tv_amount, (human, name)),那就可以直接存取類別屬性的值 i.舉個簡單的例子: 有個House,原本有一個TV(tv_amount),現在設定一個房客入住(House(1)),TV的數量就會增加1台
class House: tv_amount = 1 #類別屬性 def __init__(self, human, name): self.human = human ##實體屬性 self.name = name ##實體屬性 House.tv_amount += 1 little_turtle_home = House(1, "Turtle") print(little_turtle_home.name) # Turtle print(little_turtle_home.human) #1 print(little_turtle_home.tv_amount) #2 print(House.tv_amount)# 2 little_turtle_home1 = House(1, "Turtle") print(little_turtle_home1.tv_amount) #3 print(House.tv_amount) #3
4. 使用@classmethod,帶入cls參數也可以輕鬆存取類別屬性,其實cls代表的就是你的Class,House.tv_amount 轉成 cls.tv_amount
class House: tv_amount = 1 #類別屬性 def __init__(self, human, name): self.human = human ##實體屬性 self.name = name ##實體屬性 House.add_tv() @classmethod def add_tv(cls): cls.tv_amount += 1 little_turtle_home = House(1, "Turtle") print(little_turtle_home.name) # Turtle print(little_turtle_home.human) #1 print(little_turtle_home.tv_amount) #2 print(House.tv_amount)# 2 little_turtle_home1 = House(1, "Turtle") print(little_turtle_home1.tv_amount) #3 print(House.tv_amount) #3
希望有幫助到您~~
Reference:
https://chenhh.gitbooks.io/parallel_processing/cython/python_class.html
https://blog.csdn.net/xiaolewennofollow/article/details/51455185?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.nonecase&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.nonecase
喜欢我的文章吗?
别忘了给点支持与赞赏,让我知道创作的路上有你陪伴。
发布评论…