天天看點

參數為函數python類方法

在使用pytorch時,會使用module.apply(fn)去初始化權值,但一直沒搞懂它的原理,原來怎麼簡單,真的是從沒看源碼的程式員。

class People():
    def __init__(self, name):
        super(People, self).__init__()
        self.name = name

    def sayHello(self, fn):
        fn(self)


def hello(m):
    print(f"{m.name}: HELLO")

if __name__ == "__main__":
    p = People(name="小明")
    p.sayHello(hello)

#小明: HELLO