정적 메소드

  • 인스턴스를 생성하지 않고 클래스를 이용해서 직접 호출할 수 있는 메소드
  • 메소드 내에서 멤버 변수를 호출할 수 없지만, 클래스 변수는 호출할 수 있다.
  • 주로 공유를 목적으로 사용한다.
  • 메소드 위에 @staticmethod <- 데코레이터로 수식 (어노테이션이 아니라 데코레이터)
  • 객체를 생성하지 않고, 클래스명.정적메소드 형식으로 호출하기 때문에 접근이 쉽다.
  • 생성자 첫 자리에 self 없이 정의한다

 

class Calculator :
	
    @staticmethod
    def plus(a,b):
    	return a+b
    
    @staticmethod
    def minus(a,b):
    	return a-b
        
    @staticmethod
    def multiply(a,b):
    	return a*b
    
    @staticmethod
    def divide(a,b):
    	return a/b
        
if __name__ == '__main__' :
    print('{0}+{1}={2}'.format(7,4, Calculator.plus(7,4)))
    print('{0}-{1}={2}'.format(7,4, Calculator.minus(7,4)))
    print('{0}*{1}={2}'.format(7,4, Calculator.multiply(7,4)))
    print('{0}/{1}={2}'.format(7,4, Calculator.divide(7,4)))

 

 

 

 

 

 

 

'파이썬' 카테고리의 다른 글

예외처리  (0) 2022.11.10
상속  (0) 2022.11.09
순서가 없는 데이터의 집합 set  (0) 2022.11.02
튜플  (0) 2022.11.02
리스트와 리스트 함수 - range, numpy, sum, len, append, remove, del, index, pop, sort, sorted, reverse  (0) 2022.11.01

+ Recent posts