TIL/Python

[Python] static method와 class method

oraange 2022. 8. 17. 15:26

Static Method와 Class method


공통점

  • 인스턴스를 만들지 않아도 class의 메서드를 바로 실행할 수 있다.
class hello:
    num = 10

    @staticmethod
    def calc(x):
        return x+10

print(hello.calc(10)) # 결과: 20
class hello:
    num = 10

    @classmethod
    def calc(cls, x):
        return x+10

print(hello.calc(10)) # 결과: 20

둘 다 객체를 생성하지 않고 바로 메서드를 호출했다.

차이점

Static Method

  • 만약 hello 클래스의 num 속성에 접근하려면 어떻게 어떻게 해야할까?
    • 객체로 접근하는 것이 아니기 때문에 self.num을 사용할 순 없다.
    • 억지로 사용하고 싶다면 @staticmethod는 다음과 같이 사용해야 한다.
class hello: 
    num = 10

    @staticmethod 
    def calc(x): 
        return x + 10 + hello.num

print(hello.calc(10)) # 결과: 30
  • 이런 식으로 정적 변수로 접근해야 한다.

Class Method

  • Class Method는 메서드의 인자로 cls라는 것을 넣어준다. 이것은 자기 자신 클래스를 나타낸다.
  • cls를 통해서 클래스의 어떤 속성에도 접근할 수 있다.
class hello:
	num = 10
    @classmethod
    def calc(cls, x): 
    	return x + 10 + cls.num
        
print(hello.calc(10)) # 결과: 30

 


상속에서의 Static Method와 Class Method

Static Method

  • 부모 클래스에서 정의된 `staticmethod`는 자식 클래스에서 호출 가능
  • 클래스 변수에 접근 가능
class Parent:
    class_val = 'class variable'

    def __init__(self):
    	self.name = 'Bob'
        self.age = 29

    @staticmethod
    def check_name(name):
       	return name
        
class Child(Parent):
    pass

child = Child()
print(child.check_name('Check name!')) # 결과: Check name!
  • 하지만 인스턴스 메소드에는 접근이 불가능하다.
class Parent:
    class_val = 'class variable'

    def __init__(self):
    	self.name = 'younghun'
    	self.age = 27

    @staticmethod
    def check_name(name):
        print(Parent.class_val)
        print(self.name)
        return name
        
class Child(Parent):
    pass

parent = Parent()
print(parent.check_name('Check name!')) # 에러: NameError: name 'self' is not defined
  • 또한 부모클래스에서 호출하던 자식클래스에서 호출하던 클래스 변수를 모두 바꿀 수 있다.
class Parent:
    name = 'Bob'

    @staticmethod
    def change_name(new_name):
        Parent.name = new_name
        
class Child(Parent):
    pass

parent = Parent()
child = Child()

parent.change_name('Song')
print(parent.name, child.name) # 결과: Song Song
child.change_name('CH')
print(parent.name, child.name) # 결과: CH CH

Class Method

  • 부모 클래스에서 정의된 클래스 변수와 클래스 메소드는 자식 클래스에서도 선언이 가능
  • 클래스 변수에 접근 가능
  • 생성자 함수 포함 인스턴스 메소드 변수에 접근 불가능
class Parent:
    name = 'Bob'

    @classmethod
    def change_name(cls, new_name):
        cls.name = new_name
        
class Child(Parent):
    pass

parent = Parent()
child = Child()

parent.change_name('Song')
print(parent.name, child.name) # 결과: Song Song
child.change_name('CH')
print(parent.name, child.name) # 결과: Song CH
  • 상속에서 cls는 어떤 것을 가르키는가
class hello:
    t = '내가 상속해 줬어'

    @classmethod
    def calc(cls):
        return cls.t
    
class hello_2(hello):
    t = '나는 상속 받았어'

print(hello_2.calc()) # 결과: 내가 상속해 줬어
반응형