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)表示
比較魔法方法
算術魔法方法
iadd__(self,other)與add__(self,other)不同處在於iadd是box1 += box2的概念而add__(self,other)是將兩個相加賦予值給另一個 ⇒ box3 = box1+box2
其他魔法方法:
如果要定義list裡面放的資料型態可以用下列方式
from typing import List
Vector = List[float]
class Solution:
def runningSum(self, nums: List[int]) -> List[int]: