클래스 메서드

Python 객체 지향 프로그래밍 입문

George Boorman

Curriculum Manager, DataCamp

메서드

class Employee:
    def __init__(self, name, salary):
        self.name = name
        self.salary = salary

    def give_raise(self, amount):
        self.salary += amount


# 고유한 속성 값 emp_one = Employee("John", 40000)
emp_one.give_raise(5000) print(emp_one.salary)
45000









# 고유한 속성 값 emp_two = Employee("Jane", 60000)
emp_two.give_raise(5000) print(emp_two.salary)
65000
Python 객체 지향 프로그래밍 입문

클래스 메서드

  • 클래스 메서드를 정의할 수 있음
  • 객체 수준 데이터를 못 쓰므로 범위를 좁게
class MyClass:
    # 데코레이터로 클래스 메서드 선언
    @classmethod

# cls 인자는 클래스를 가리킴 def my_awesome_method(cls, args...): # 여기서 처리 # 인스턴스 속성 사용 불가
# 객체가 아닌 클래스로 호출 MyClass.my_awesome_method(args...)
  • self처럼 cls도 관례일 뿐, 다른 이름도 가능
Python 객체 지향 프로그래밍 입문

대체 생성자

class Employee:
  def __init__(self, name, salary):
      self.name = name
      self.salary = salary

@classmethod def from_file(cls, filename): with open(filename, "r") as f: # 첫 번째 줄 읽기 name = f.readline().strip() # 두 번째 줄을 정수로 읽기 salary = int(f.readline().strip())
return cls(name, salary)
  • 대체 생성자 제공
  • __init__()는 하나만 가능

 

  • 클래스 메서드로 객체 생성
  • return으로 객체 반환
  • cls(...)__init__(...) 호출
Python 객체 지향 프로그래밍 입문

대체 생성자

class Employee:
  def __init__(self, name, salary):
      self.name = name
      self.salary = salary
  @classmethod
  def from_file(cls, filename):
      with open(filename, "r") as f:
          name = f.readline().strip()
          salary = int(f.readline().strip())
      return cls(name, salary)  

Employee.txt

John Smith 이름과 40000 급여가 포함된 텍스트 파일

# Employee()를 직접 호출하지 않고 생성
emp = Employee.from_file("employee_data.txt")
print(emp.name)
John Smith
Python 객체 지향 프로그래밍 입문

클래스 메서드를 쓸 때

  • 대체 생성자

  • 인스턴스 속성이 필요 없는 메서드

  • 클래스의 인스턴스를 하나로 제한

    • 데이터베이스 연결
    • 구성 설정
Python 객체 지향 프로그래밍 입문

Vamos praticar!

Python 객체 지향 프로그래밍 입문

Preparing Video For Download...