파이썬 연산자 오버로딩

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을 만들려면?

  • __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...