객체 지향 프로그래밍 기초

Python 중급 객체 지향 프로그래밍

Jake Roach

Data Engineer

클래스 정의하기

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

# This invokes a call to __init__
john = Person("John Casey", 38)
  • class 키워드로 클래스 정의
  • __init__는 생성자이며 새 객체 생성 시 호출됨
  • self는 현재 인스턴스를 참조
Python 중급 객체 지향 프로그래밍

인스턴스 속성

class Person:
  def __init__(self, name, age):
    self.name = name
    self.age = age
# Create an instance of Person
sarah = Person("Sarah Walker", 31)
sarah.age  # Retrieve the age instance attribute
  • 클래스의 객체에 연결됨
  • self.<attribute-name> 구문으로 설정/조회
  • <object-name>.<attribute-name>로 접근
Python 중급 객체 지향 프로그래밍

클래스 속성

  • 클래스 자체에 속함
  • 클래스 객체 없이도 조회 가능
  • 모든 객체에 동일해야 하는 데이터 저장
class Person:
  residence = "Planet Earth"
  ...
# Accessed without an instance
print(Person.residence)
Planet Earth
Python 중급 객체 지향 프로그래밍

인스턴스 메서드

class Person:
  ...
  def introduce(self):
      print(f"Hello, my name is {self.name}")
chuck = Person("Chuck", 32)
chuck.introduce()  # Called on a Person object

$$

  • 호출하려면 해당 클래스의 객체가 필요
  • 첫 번째 매개변수로 self 사용
Python 중급 객체 지향 프로그래밍

클래스 메서드

class Person:
  @classmethod
  def wake_up(cls):
      print("Time to start your day!")
# Calling a class method
Person.wake_up()

$$

  • @classmethod 데코레이터 사용
  • 호출 시 클래스 객체가 필요하지 않음
Python 중급 객체 지향 프로그래밍

상속

상속은 클래스 간 코드 재사용을 가능하게 합니다

  • 자식 클래스(Employee)는 부모 클래스(Person)의 모든 기능을 상속
  • "is-a" 관계
  • 추가 기능 구현 가능
    • 속성
    • 메서드
class Person:
  def __init__(self, name, age):
    self.name
    self.age = age

  def introduce(self):
      print(f"Hello, my name is {self.name}")
class Employee(Person):
  def __init__(self, name, age, title):
    Person.__init__(self, name, age)
    self.title = title

  def change_position(self, new_title):
      self.title = new_title
Python 중급 객체 지향 프로그래밍

상속

lester = Employee("Lester", 26, "Technician")
lester.introduce()  # Inherited from Person
print(lester.title)
Hello, my name is Lester
Technician
lester.change_position("Cashier")
print(lester.title)
Cashier
Python 중급 객체 지향 프로그래밍

super()

class Employee(Person):
  def __init__(self, name, age, title):
    # Uses name of the parent class
    Person.__init__(self, name, age)

    self.title = title
  ...
  • 클래스명, __init__()

super() 사용

class Employee(Person):
  def __init__(self, name, age, title):
    # 클래스명 대신 super()
    super().__init__(name, age)

    self.title = title
  ...
  • super(), __init__()
  • self를 전달할 필요 없음
Python 중급 객체 지향 프로그래밍

오버라이딩

자식이 부모에게서 상속한 메서드를 새 방식으로 구현합니다

class Employee(Person):
  ...
  def introduce(self):
      print(f"""My name is {self.name},
        I am a {self.title}""")
lester = Employee("Lester", 26, "Technician")
lester.introduce()
My name is Lester, I am a Technician
Python 중급 객체 지향 프로그래밍

오버로딩

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

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

$$

  • 클래스에 대해 파이썬 연산자 동작을 사용자 지정
  • __eq__()== 오버로딩에 사용

$$

$$

$$

$$

# Compare two Person objects
chuck = Person("Charles Carmichael")
charles = Person("Charles Carmichael")
print(chuck == charles)
True
Python 중급 객체 지향 프로그래밍

Passons à la pratique !

Python 중급 객체 지향 프로그래밍

Preparing Video For Download...