简体   繁体   中英

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. 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. Try instead initializing variables during object initialization:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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