클래스의 메소드(method)

Amps93·2023년 2월 19일
0

class

목록 보기
3/3

정적 메소드

  1. 인스턴스 메소드 (Instance method)

    • self가 들어감
    • 객체의 고유한 속성 값을 사용
  2. 클래스 메소드 (class method)

    • @classmethod 데코레이터를 사용
    • cls 인자를 받음
    • cls는 클래스를 뜻함
    • 클래스 변수를 컨트롤할 때 사용
  3. 스태틱 메소드 (static method)

    • 인자를 받지 않음 (self, cls 등)
    • @staticmethod 데코레이터를 사용
class Rectangle:
    count = 0  # 클래스 변수
 
    def __init__(self, width, height):
        self.width = width
        self.height = height
        Rectangle.count += 1
 
    # 인스턴스 메서드
    def calcArea(self):
        area = self.width * self.height
        return area
 
    # 정적 메서드
    @staticmethod
    def isSquare(rectWidth, rectHeight):
        return rectWidth == rectHeight   
 
    # 클래스 메서드
    @classmethod
    def printCount(cls):
        print(cls.count)   
 
 
# 테스트
square = Rectangle.isSquare(5, 5)        
print(square)   # True        
 
rect1 = Rectangle(5, 5)
rect2 = Rectangle(2, 5)
rect1.printCount()  # 2 

추상 메소드

  • 메소드의 목록만 가진 클래스
  • 상속받는 클래스에서 메소드 구현을 강제하기 위해 사용
  • 추상 메소드 (abstract method)
  • abstractmethod 데코레이터를 사용
from abd import *

class StudentBase(metaclass=ABCMeta):
  @abstractmethod
  def study(self):
    pass
    
  def go_to_school(self):
    pass
    
class Student(StudentBase):
  def Student()
    print('공부하기')
    
james = Student()
james.study()

# 실행 결과
'''
Traceback (most recent call last):
  File "C:\project\class_abc_error.py", line 16, in <module>
    james = Student()
TypeError: Can't instantiate abstract class Student with abstract methods go_to_school 
'''
# Student 클래스가 go_to_school 메소드를 구현하지 않아 오류 발생
  • 메소드 구현 후 재실행
from abc import *
 
class StudentBase(metaclass=ABCMeta):
    @abstractmethod
    def study(self):
        pass
 
    @abstractmethod
    def go_to_school(self):
        pass
 
class Student(StudentBase):
    def study(self):
        print('공부하기')
 
    def go_to_school(self):
        print('학교가기')
 
james = Student()
james.study()
james.go_to_school()

# 실행 결과
'''
공부하기
학교가기
'''
  • 추상 클래스는 인스턴스로 만들 수 없음
  • 예시
>>> james = StudentBase()
Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    james = StudentBase()
TypeError: Can't instantiate abstract class StudentBase with abstract methods go_to_school, study
  • 추상 클래스는 인스턴스로 만들 때는 사용하지 않으며 오직 상속에만 사용
  • 그리고 파생 클래스에서 반드시 구현해야 할 메소드를 정해 줄 때 사용

출처
1. https://zzsza.github.io/development/2020/07/05/python-class/
2. https://dojang.io/mod/page/view.php?id=2389

profile
머신러닝 개발자

0개의 댓글