简体   繁体   English

我正在Python 3中的Dictionary中调用函数

[英]I am calling functions inside a Dictionary in Python 3

I have a class where I have 3 simple functions and I package all of them in a dictionary. 我有一堂课,我有3个简单的函数,并将它们全部打包在字典中。 The objective is to be able to loop through the dictionary calling the functions, however, I am getting several errors: 目的是能够遍历调用函数的字典,但是,我遇到了几个错误:

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}

The results I get are the following: 我得到的结果如下:

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'

Any clues what it could be the problem? 任何线索可能是什么问题? Thanks.- 谢谢。-

variables is a class variable, but you're trying to call instance methods. variables是一个类变量,但是您正在尝试调用实例方法。 Try instead initializing variables during object initialization: 尝试在对象初始化期间初始化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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM