0

I'm trying to use eval() to run dynamic code, but it seems to reject object-based methods:

def GetHelp():
    return 'Help'

class MyClass:
    def __init__(self):
        self.child = 5
    def GetChild():
        return self.child

x = eval('Get{}()'.format('Help'))
print(x)

obj = MyClass()
y = eval('obj.Get{}()'.format('Child'))
print(y)

The above code gives me:

Help
Traceback (most recent call last):
  File "/Users/kakyo/Desktop/0.Dev/playground/python/hello_eval.py", line 14, in <module>
    y = eval('obj.Get{}()'.format('Child'))
  File "<string>", line 1, in <module>
TypeError: GetChild() takes 0 positional arguments but 1 was given

I tried to add obj to locals:

y = eval('obj.Get{}()'.format('Child'), {'obj': obj})

but got the same error.

DeepSpace
  • 78,697
  • 11
  • 109
  • 154
kakyo
  • 10,460
  • 14
  • 76
  • 140

1 Answers1

3

The error is unrelated to the fact you used eval (but do not use eval). It is because GetChild does not accept self (or actually any other argument) as the instance in its signature.

It should be def GetChild(self)

But (if it wasn't clear already) eval should be avoided at all costs and is very rarely the only solution to a given problem.

In this case, it is preferable to use getattr:

obj = MyClass()
y = getattr(obj, 'Get{}'.format('Child'))()
print(y)
DeepSpace
  • 78,697
  • 11
  • 109
  • 154