Lập trình Hướng đối tượng Nâng cao với Python
Jake Roach
Data Engineer
class Person:
def __init__(self, name):
self.name = name
def __eq__(self, other):
return self.name == other.name
Tùy biến chức năng của ==
__eq__()self và 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
# Tạo hai đối tượng Team, thử cộng chúng
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 là danh sách tên
self.team_members = team_members
def __add__(self, other):
# Cộng các Team tạo ra Team lớn hơn
return Team(self.team_members + other.team_members)
__add__() để nạp chồng +self và other được truyền vào __add__()Team mới từ team_members của các đối tượng được “cộng”# Tạo hai đối tượng Team
rookies = Team(["Casey", "Emmitt"])
veterans = Team(["Mike", "Chuck"])
# Thử cộng hai Team này với nhau
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):
# Dùng toán tử + để tạo
# Team với tên của mỗi Employee
return Team([self.name, other.name])
Nếu muốn tạo Team bằng cách kết hợp các Employee thì sao?
__add__ được cài trong lớp EmployeeTeam mới từ danh sách tên EmployeeEmployee là một Team# Tạo hai đối tượng Employee
anna = Employee("Anna", "Technical Specialist")
jeff = Employee("Jeffrey", "Musician")
# Thử cộng hai đối tượng để tạo một team
audio_team = anna + jeff
print(type(audio_team))
print(audio_team.team_members)
Team
["Anna", "Jeffrey"]
| Toán tử | Magic Method | Loại |
|---|---|---|
| - | __sub__ |
Số học |
| != | __ne__ |
So sánh |
| < | __lt__ |
So sánh |
| > | __gt__ |
So sánh |
| += | __iadd__ |
Gán |
| and | __and__ |
Logic |
| in | __contains__ |
Thành viên |
| is | __is__ |
Danh tính |
... Và còn rất nhiều nữa!
Lập trình Hướng đối tượng Nâng cao với Python