본문 바로가기
Programming/Python

[Python] bound / unbound method란? (feat. static method)

by a voyager 2021. 4. 29.
728x90
반응형

이 포스팅의 핵심 포인트 

  • bound 와 unbound method의 정의와 구분 ('self' argument)
  • 클래스 밖에서 정의된 함수를 클래스의 매서드로 포함시키는 방법 
  • static method의 정의와 사용법 

bound method란? 

클래스는 여러 멤버 함수들을 포함할 수 있다. 이 멤버 함수들은 공통적으로 'self'를 첫 번째 입력 인자를 가진다. 이것은 이 함수가 어떤 클래스에 속해 있는 method라는 것을 의미한다. 이것을 bound method라고 한다. 

 

다음의 예제를 생각해 보자. 클래스 A는 bar라는 이름의 bound method를 가지고 있다. 객체를 생성해 bar 메서드에 접근해 보자. 

class A: 
    def bar(self): 
        print("bar")
        
    def foo(): 
        print("foo is not a bound method")

 

우선 클래스 A로부터 a라는 객체(instance)를 생성한다. 

a = A()

 

다음과 같이 bar에 접근할 수 있다. () 없이 출력하면 클래스 A의 bar가 bound method라는 것을 보여준다. 

a.bar 

bar는 bar를 출력한다. 

a.bar()

Adding a method to an existing class 

이제 새로운 함수를 만들어 기존에 만들어 놓은 클래스의 메서드로 사용해보자. 아래와 같이 self를 인수로 가지는 fooFighters를 만든다. 이 함수는 어느 클래스에도 속하지 않은 함수이다. 

def fooFighters(self):
     print ("fooFighters")

 

이것을 위 클래스 A의 매소드로 사용하기 위해서 다음과 같이 bound를 해준다. 

A.fooFighters = fooFighters 

# or use descriptor method __get__

A.fooFighters = fooFighters.__get__(A)

 

그리고 함수의 정보를 출력하면 A에 속한 bound 매서드라는 것을 볼 수 있다. 

a.fooFighters

a.fooFighters()

unbound method란? 

foo()메서드는 어떤 input 인수를 가지지 않는다. 이것은 unbound method이다. 이 매서드는 클래스 A 안에 위치해 있지만 매서드로 호출(callable)할 수 없는 함수이다. 호출하려 한다면 다음과 같이 에러를 낸다. 

a.foo() 

Static method 

unbound method를 호출하기 위해서 static method를 생각할 수 있다. 두 가지 방법이 있다. 

 

  1. staticmethod() 
  2. decorator 사용 

아래의 실행에서 볼 수 있듯이, static method는 객체(instance)를 생성할 필요가 없다. 그 이유는 static method는 객체와 상관없이 동일한 기능을 수행하기 때문이다. 

# staticmethod 

A.foo = staticmethod(A.foo)
A.foo()

# decorator 

class A: 
    def bar(self): 
        print("bar")
       
    @staticmethod
    def foo(): 
        print("foo is not a bound method")
        
A.foo() 

Example:

math 클래스의 sqrt() 나 ceil()은 항상 동일한 기능을 수행하는 static method 이므로 클래스의 매서드로 바로 호출이 가능하다. 

import math 

print(math.sqrt(4.0)) 
# >> 2.0 

print(math.ceil(4.3)) 
# >> 4.0 

 

728x90
반응형

댓글