gpt4 book ai didi

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

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

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

这会起作用。

关于python - 在 Python 类中定义和调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51711189/

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