gpt4 book ai didi

python - 可以用普通函数替换方法吗?

转载 作者:太空宇宙 更新时间:2023-11-04 07:34:32 25 4
gpt4 key购买 nike

这按预期工作,但我对这种方法不太确定。安全吗?它是 Pythonic 的吗?

class Example:
def __init__(self, parameter):
if parameter == 0:
# trivial case, the result is always zero
self.calc = lambda x: 0.0 # <== replacing a method
self._parameter = parameter

def calc(self, x):
# ... long calculation of result ...
return result

(如果 Python2 和 Python3 之间有任何区别,我只使用 Python3。)

最佳答案

这很令人困惑。如果其他人阅读它,他们将不明白发生了什么。只需在方法的开头放置一个 if 语句即可。

def calc(self, x):
if self.parameter == 0:
return 0
# ... long calculation of result ...
return result

此外,如果您在使用 0 初始化后更改 self.parameter,您的函数将不再起作用。

关于python - 可以用普通函数替换方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39384922/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com