在 Python 类中定义和调用函数

Dan*_*nny 1 python

我正在创建一个类,我希望在该类的方法中调用用户定义的函数。我还想在类定义中定义函数。但是,当我调用该类时,收到错误消息name *whatever function* is not defined

例如,这样的事情:

class ExampleClass():

    def __init__(self, number):
        self.number = number

    def plus_2_times_4(x):
        return(4*(x + 2))

    def arithmetic(self):
        return(plus_2_times_4(self.number))
Run Code Online (Sandbox Code Playgroud)

但是当我打电话时:

instance = ExampleClass(number = 4)
instance.arithmetic() 
Run Code Online (Sandbox Code Playgroud)

我收到错误消息。

所以基本上我想在一个步骤 ( def plus_2_times_4) 中定义函数,并在另一个步骤 (d ef arithmetic...) 中定义方法时使用该函数。这可能吗?

非常感谢!

mus*_*rat 5

定义和调用plus_2_times_4self,即:

class ExampleClass():

    def __init__(self, number):
        self.number = number

    def plus_2_times_4(self,x):
        return(4*(x + 2))

    def arithmetic(self):
        return(self.plus_2_times_4(self.number))
Run Code Online (Sandbox Code Playgroud)

这将起作用。


Its*_*mmy 5

使用以下方法调用该方法ExampleClass.plus_2_times_4

class ExampleClass():

    def __init__(self, number):
        self.number = number

    def plus_2_times_4(x):
        return(4*(x + 2))

    def arithmetic(self):
        return(ExampleClass.plus_2_times_4(self.number))
Run Code Online (Sandbox Code Playgroud)

或者,使用@staticmethod装饰器并使用正常的方法调用语法调用该方法:

class ExampleClass():

    def __init__(self, number):
        self.number = number

    @staticmethod
    def plus_2_times_4(x):
        return(4*(x + 2))

    def arithmetic(self):
        return(self.plus_2_times_4(self.number))
Run Code Online (Sandbox Code Playgroud)

装饰@staticmethod器确保self永远不会隐式传入,就像通常的方法一样。