多載 Python 運算子

Python 物件導向程式設計進階

Jake Roach

Data Engineer

多載比較運算子

class Person:
  def __init__(self, name):
      self.name = name

  def __eq__(self, other):
      return self.name == other.name

自訂 == 的功能

  • 使用 __eq__() 魔術方法
  • 接收 selfother
  • 回傳布林值
bryce = Person("Bryce")
orion = Person("Orion")
print(bryce == orion)
False
chuck = Person("Charles Carmichael")
charles = Person("Charles Carmichael")
print(chuck == charles)
True
Python 物件導向程式設計進階

加總兩個物件

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'
Python 物件導向程式設計進階

多載 + 運算子

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__() 魔術方法來多載 +
  • selfother 會傳入 __add__()
  • 以兩者的 team_members 建立新的 Team 物件
Python 物件導向程式設計進階

加總兩個物件

# 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"]
Python 物件導向程式設計進階

用 + 建立新型別物件

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
Python 物件導向程式設計進階

相加兩個物件建立新物件

# 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"]
Python 物件導向程式設計進階

多載其他運算子

運算子 魔術方法 類型
- __sub__ 算術
!= __ne__ 比較
< __lt__ 比較
> __gt__ 比較
+= __iadd__ 指派
and __and__ 邏輯
in __contains__ 成員
is __is__ 識別

 

 

 

 

 

 

 

…還有很多!

Python 物件導向程式設計進階

一起來練習吧!

Python 物件導向程式設計進階

Preparing Video For Download...