[Python] __call__함수

2021. 7. 26. 21:53Python

728x90

파이썬은 __(double underscore)로 시작하는 magic method로 클래스가 특별한 동작을 수행하게 할 수 있음

함수호출처럼 클래스의 객체도 호출할 수 있게 만들어주려면

__call__이라는 매직매소드 필요

callable함수를 통해 호출가능한 객체인지 확인할 수 있다.

(활용 예)

출처 : https://github.com/rosinality/style-based-gan-pytorch/blob/master/model.py

class EqualLR:
    def __init__(self, name):
        self.name = name

    def compute_weight(self, module):
        weight = getattr(module, self.name + '_orig')
        fan_in = weight.data.size(1) * weight.data[0][0].numel()

        return weight * sqrt(2 / fan_in)

    @staticmethod
    def apply(module, name):
        fn = EqualLR(name)

        weight = getattr(module, name)
        del module._parameters[name]
        module.register_parameter(name + '_orig', nn.Parameter(weight.data))
        module.register_forward_pre_hook(fn)

        return fn

    def __call__(self, module, input):
        weight = self.compute_weight(module)
        setattr(module, self.name, weight)


def equal_lr(module, name='weight'):
    EqualLR.apply(module, name)

    return module
728x90

'Python' 카테고리의 다른 글

[python] *args , **kwargs  (0) 2021.07.19
hasattr(object, name) / getattr(object, name) / setattr(object, name)  (0) 2021.06.15
class 이름/ class 변수 참조  (0) 2021.06.15
__getitem__  (0) 2021.05.21
Python argparse  (0) 2021.05.09