Concept:

python

magic method


Filename:

#comments

https://replit.com/@dngg6688/AI12lesson6#main.py



class Dog():
    def __init__(self,name,height):
        self.name=name
        self.height = height
		def bark(self):
        print(f"{self.name} is barking")

    def __str__(self):
        return f"{self.name} and high is {self.height}cm"

    def __repr__(self):
        return  f"{self.name}"

    def __lt__(self, other_dog):
        return  self.height < other_dog.height

dogs = [Dog("Mike",30),Dog("A",15),Dog("Pluto",10)]

print(Dog("Mike",30))

print("before:",dogs)
dogs.sort()
print("after:",dogs)

#算術魔法方法

class Depth:
    def __init__(self,depth):
        self.depth = depth

    def __str__(self):
        return f"{self.depth}cm"

    def __add__(self, other):
       return Depth(self.depth+other.depth)

box1_depth  = Depth(10)
box2_depth  = Depth(15)

box3_depth=box1_depth+box2_depth

print(box3_depth)

呼叫物件時會傳回裡面字串

呼叫多個物件所形成的集合會回傳字串

比較物件大小提供比較方法

Mike and high is 30cm

before: [Mike, A, Pluto]

after: [Pluto, A, Mike]

若沒有__add__(self)方法會出現

TypeError: unsupported operand type(s) for +: 'Depth' and 'Depth'

25cm

其實只是在做box1_depth.add(box2_depth)


Summary:

magic method:在類別內有特殊作用的方法以def XX(self)表示

比較魔法方法

https://s3-us-west-2.amazonaws.com/secure.notion-static.com/63a1c8ff-f334-4560-a3ae-fd847806b7d1/Untitled.png

https://s3-us-west-2.amazonaws.com/secure.notion-static.com/932bb90a-4728-45f2-a172-60b6c8142d64/Untitled.png

算術魔法方法

https://s3-us-west-2.amazonaws.com/secure.notion-static.com/1c026577-02ba-4ba6-ba5e-d09b1ee30817/Untitled.png

iadd__(self,other)與add__(self,other)不同處在於iadd是box1 += box2的概念而add__(self,other)是將兩個相加賦予值給另一個 ⇒ box3 = box1+box2

https://s3-us-west-2.amazonaws.com/secure.notion-static.com/2817873e-5706-4792-bb13-2bc0b588ee82/Untitled.png

其他魔法方法:

https://s3-us-west-2.amazonaws.com/secure.notion-static.com/a124efa8-f5fb-4e9f-b2dd-e5d8120c43e6/Untitled.png

https://s3-us-west-2.amazonaws.com/secure.notion-static.com/f16bc4f0-e9a6-4378-b592-051d72c6308c/Untitled.png

如果要定義list裡面放的資料型態可以用下列方式

from typing import List
Vector = List[float]

class Solution:
	def runningSum(self, nums: List[int]) -> List[int]: