gpt4 book ai didi

python - 我在 Python 3 的字典中调用函数

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

我有一个类,其中有 3 个简单函数,我将它们全部打包在字典中。目标是能够遍历调用函数的字典,但是,我遇到了几个错误:

class Testa(object):
def __init__(self, debt = None, equity = None):
self.debt = debt
self.equity = equity
def tutu():
print('hola')
def foo(self):
print('hello')
def bar(self, debt=None, equity=None):
return equity - debt

variables = {'tutu':tutu,'foo':foo,'bar':bar}

我得到的结果如下:

ra =Testa()
ra.variables['tutu']()
>>> hola
ra.variables['foo']()
>>> TypeError: foo() missing 1 required positional argument: 'self'
ra.variables['bar'](debt = 300, equity=400)
>>> TypeError: bar() missing 1 required positional argument: 'self'

任何线索可能是什么问题?谢谢。-

最佳答案

variables 是一个类变量,但您正在尝试调用实例方法。尝试在对象初始化期间初始化 variables:

class Testa(object):
def __init__(self, debt = None, equity = None):
self.debt = debt
self.equity = equity
self.variables = {'tutu': self.tutu, 'foo':self.foo, 'bar': self.bar}
def tutu(self):
print('hola')
def foo(self):
print('hello')
def bar(self, debt=None, equity=None):
return equity - debt

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

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