Python 物件導向程式設計進階
Jake Roach
Data Engineer
class Person:
def __init__(self, name):
self.name = name
def __eq__(self, other):
return self.name == other.name
自訂 == 的功能
__eq__() 魔術方法self 與 otherbryce = Person("Bryce")
orion = Person("Orion")
print(bryce == orion)
False
chuck = Person("Charles Carmichael")
charles = Person("Charles Carmichael")
print(chuck == charles)
True
class Team:
def __init__(self, team_members):
self.team_members = team_members
# Create two Team objects, attempt to add them
rookies = Team(["Casey", "Emmitt"])
veterans = Team(["Mike", "Chuck"])
dream_team = rookies + veterans
Traceback (most recent call last):
File "<stdin>", line 8, in <module>
TypeError: unsupported operand type(s) for +: 'Team' and 'Team'
class Team:
def __init__(self, team_members):
# team_members is a list of names
self.team_members = team_members
def __add__(self, other):
# Adding Team objects creates a larger Team
return Team(self.team_members + other.team_members)
__add__() 魔術方法來多載 +self 與 other 會傳入 __add__()team_members 建立新的 Team 物件# Create two Team objects
rookies = Team(["Casey", "Emmitt"])
veterans = Team(["Mike", "Chuck"])
# Attempt to add these two Teams together
dream_team = rookies + veterans
print(type(dream_team))
print(dream_team.team_members)
Team
["Casey", "Emmitt", "Mike", "Chuck"]
class Team:
def __init__(self, team_members):
self.team_members = team_members
class Employee:
def __init__(self, name, title):
self.name = name
self.title = title
def __add__(self, other):
# Use the + operator to create a
# Team with the name of each Employee
return Team([self.name, other.name])
如果想把多個 Employee 合成一個 Team 呢?
Employee 類別中實作 __add__Employee 的姓名清單建立新的 Team 物件Employee 的結果是一個 Team# Create two Employee objects
anna = Employee("Anna", "Technical Specialist")
jeff = Employee("Jeffrey", "Musician")
# Now, attempt to add these together to create a team
audio_team = anna + jeff
print(type(audio_team))
print(audio_team.team_members)
Team
["Anna", "Jeffrey"]
| 運算子 | 魔術方法 | 類型 |
|---|---|---|
| - | __sub__ |
算術 |
| != | __ne__ |
比較 |
| < | __lt__ |
比較 |
| > | __gt__ |
比較 |
| += | __iadd__ |
指派 |
| and | __and__ |
邏輯 |
| in | __contains__ |
成員 |
| is | __is__ |
識別 |
…還有很多!
Python 物件導向程式設計進階