Skip to main content
 首页 » 编程设计

python之在 Python 类中定义和调用函数

2025年05月04日12www_RR

我正在创建一个类,我希望在该类的方法中调用用户定义的函数。我还想在类定义中定义函数。但是,当我调用该类时,我收到错误消息 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)) 

但是当我打电话时:

instance = ExampleClass(number = 4) 
instance.arithmetic()  

我收到错误消息。

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

提前致谢!

请您参考如下方法:

用self定义并调用plus_2_times_4,即:

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)) 

这会起作用。