youngfromnowhere

[Python] Python의 Method Call 본문

Python

[Python] Python의 Method Call

곽일땡 2022. 10. 31. 19:44

Class 내부에 정의된 method를 호출하는 방법에는 두 가지가 있다.

첫 번째는 method명 앞에 instance명을 prefix로 붙이는 것이다.

즉, object 'my_object'가 class 'MyClass'의 instance이고, MyClass 내에

'__mymethod__'가 정의된 경우.

my_object.__mymethod__()

로 method를 호출할 수 있다.

 

두 번째는 class명을 prefix로 붙이고, instance를 argument로 입력하는 것이다.

MyClass.__mymethod__(my_object)

사실 첫 번째 method call은 python 내부에서 두 번째 형식에 맞게 변환된다.

my_object.__mymethod__() => type(my_object).__mymethod__(my_object)

Class 내에서 method를 정의할 때 self를 argument로 명시하는 이유가 이것이다. 실제로 method는 호출될 때 instance를 argument로 받는다!

 

Python의 namespace에는 instance namespace와 class namespace가 있는데, class namespace에는 해당 class의 모든 instance에서 공유되는 attribute들이 포합된다. instance namespace에는 각 instance마다 개별적인 값을 갖는 attribute들이 포함된다.

즉, instance namespace에는, __init__에서 정의되는 'self'가 앞에 붙은 instance variable들만이 포함되고, class 내에 정의되는 method들은 엄연히 class namespace에 포함된다.

Method는 instance가 아니라 엄연히 class 내부에 정의되며, 따라서 method를 호출할 때는 class명을 prefix로 쓰는게 논리적이다. 이것이 첫번째 방식의 call이 내부적으로 두번째 방식으로 변환하는 과정을 거치는 이유이다.

 

Method call에서 특이한 것은, 인자로 받는 object (위의 my_object)가 prefix로 명시된 class의 instance가 아니어도 된다는 것이다. Method명 앞의 prefix는 method의 소속을 밝히기 위한 것일 뿐이다.

따라서 다음과 같은 method call이 가능하다.

class C:
    def __init__(self):
        self._x = "this is C()._x"
    def getcx(self):
        return self._x
class D:
    def __init__(self):
        self._x = "this is D()._x"
    def getdx(self):
        return self._x

if __name__ == "__main__" :
    c = C()
    d = D()
    print("C.getcx(d) returns : " + C.getcx(d))
    print("D.getdx(c) returns : " + D.getdx(c))

결과는

C.getcx(d) returns : this is D()._x
D.getdx(c) returns : this is C()._x

위에 줄줄이 복잡하게 설명했지만, 더욱 간단하게 말하자면, 그냥 입력받은 객체의 _x 변수를 return하는 두개의 C.getcx(), D.getdx()라는 method만이 존재한다는 것이다. 두 method에 C의 instance를 전달하든, D의 instance를 전달하든, 두 method는 똑같이 전달받은 객체 내부의 객체변수를 반환할 뿐이다.

'Python' 카테고리의 다른 글

[Python] python의 special methods  (0) 2022.11.17
[Python] Decorator3. Property  (0) 2022.11.16
[Python] Decorator 2. abstractmethod()  (0) 2022.11.15
[Python] Decorator  (0) 2022.11.07
[Python] 가상환경  (0) 2022.11.03