반응형
  • 인스턴스 메소드
    • 인스턴스 속성에 접근하는 메소드
    • self 를 파라미터로 받는다.
  • 클래스 메소드
    • 클래스 속성에 접근하는 메소드
    • 클래스를 의미하는 cls 를 파라미터로 받는다
    • @classmethod 를 붙인다
class Unit:
  count = 0
  def __init__(self, name, weight, height, hidden):
    self.name=name
    self.weight=weight
    self.height=height
    self.__hidden=hidden
    Unit.count +=1
    print(f"{self.name} Unit 생성")
  
  def __str__(self):
    return f"name={self.name} weight={self.weight} height={self.height}"
  
  # 인스턴스 메소드
  # 인스턴스 속성에 접근하는 메소드
  def loseWeight(self, value):
    self.weight = self.weight - value
    print(f"무게가 {value} 만큼 줄었습니다. 현재는 {self.weight} 입니다.")

  # 클래스 메서드
  # 클래스 속성에 접근하는 메소드
  # cls를 파라미터로 받는다
  @classmethod
  def print_count(cls):
    print(f"생성된 Unit 개수 = {cls.count}")
    
unit1 = Unit("Unit1", 20, 30, "magic")
print(unit1)
print(unit1.loseWeight(10))
Unit.print_count()

# OUTPUT
Unit1 Unit 생성
name=Unit1 weight=20 height=30
무게가 10 만큼 줄었습니다. 현재는 10 입니다.
생성된 Unit 개수 = 2
  • 정적 메소드
    • 인스턴스를 만들 필요가 없다.
    • self 를 받지 않는다.
    • @staticmethod 를 붙인다
class Math:
  @staticmethod
  def add(x,y):
    return x+y

print(Math.add(3,5))
  • 매직 메소드
    • __이름__ 형태로 되어있다.
    • __init__ : 객체가 생성될때 실행되는 메소드
    • __str__ :  객체를 출력하는 메소드

 

728x90
반응형

+ Recent posts