【发布时间】:2021-05-10 22:39:27
【问题描述】:
我的目标:传递对函数的引用,并能够在以后更新该函数。
在 Python 中,我相信函数是通过引用传递的,但函数的引用被认为是不可变的。因此,该功能以后无法更新。
这个问题是核心问题:Python functions call by reference
答案都指向解决方法:在可变类型中传递函数,例如 list 或 dict。
我想知道:有更直接的方法吗?可能有一些functools 函数、types 实用程序或外部库可以实现这种行为?
示例代码
**更新**:我对公开foo._on_call 不感兴趣。我试图通过引用从外部更改on_call,而不是直接在foo 对象上实际操作。
from typing import Callable, List
class Foo:
def __init__(self, on_call: Callable[[], int]):
self._on_call = on_call
def __call__(self) -> int:
return self._on_call()
def do_something() -> int:
return 0
def do_something_else() -> int:
return 1
foo = Foo(do_something)
do_something = do_something_else # Updating do_something
print(do_something()) # This prints 1 now
print(foo()) # This still prints 0, I want this to print 1 now too
已知(不受欢迎的)解决方法:
- 在列表中传递
do_something - 重新创建
foo对象 - 公开
Foo的_on_call属性或使用property装饰器
Python 版本:3.8
【问题讨论】:
-
更直接的方式:
foo._on_call = do_something_else -
你能提供更多的背景信息吗?这似乎是一个XY problem。
标签: python function pass-by-reference immutability