Skip to main content
 首页 » 编程设计

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

2025年05月04日15me-sa

这按预期工作,但我对这种方法不太确定。安全吗?它是 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,您的函数将不再起作用。