0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【ひとくちメモ】Pythonの関数ポインタ

Last updated at Posted at 2024-01-09

概要

Pythonのクラスに関数を登録するときの挙動

うまく行かない場合

class Hoge:
    def __init__(self):
        self.func = lambda: None
        self.trigger = self.func

def hello():
    print('hello')

hoge = Hoge()
hoge.func = hello
hoge.trigger() # 出力なし

hoge.trigger()をするとhelloが実行されてほしいが、実際には何も出力されない

うまくいく場合

class Hoge:
    def __init__(self):
        self.func = lambda: None
        self.trigger = lambda: self.func() # 変更箇所

def hello():
    print('hello')

hoge = Hoge()
hoge.func = hello
hoge.trigger() # 出力: hello

解説

self.trigger = self.funcだと関数ポインタが渡されるのであとからself.funcを変更しても最初に指定したlambda: Noneが呼ばれ続ける

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?