0

If I have the following code:

class foo:
    def __init__(self):
        self.w = 5
        self.z = 10

def sum(obj,x,y):
    return obj.x+obj.y

f = foo()
print sum(foo,'x','y')

How would I create a function that takes in two unkown variable names and returns the sum of those variables variables?

In this case the example should print 15. EDIT: Typo for the last line it should say print sum(foo,'w','z')

  • 2
    How do you expect it to figure out that the string `'x'` is supposed to mean `foo.w` and the string `'y'` is supposed to mean `foo.z`? – abarnert May 02 '18 at 21:49
  • 5
    I think you _might_ be looking for [`getattr`](https://docs.python.org/3/library/functions.html#getattr) here. But usually, when you're using `getattr`, it's a sign of [an XY problem](https://meta.stackexchange.com/questions/66377/). Why do you want to `print sum(foo, 'x', 'y')` instead of `sum(foo.x, foo.y)` (or whatever you actually wanted) in the first place? – abarnert May 02 '18 at 21:51
  • I think you mean `sum(f,'w','z')`? – Aran-Fey May 02 '18 at 21:51

1 Answers1

-2

All (I think?) python objects have a built-in __getattribute__ method. Use it like this:

def sum(obj,x,y):
    return obj.__getattribute__(x)+obj.__getattribute__(y)

The method takes a string, and "unpacks" it to being a variable name.

mypetlion
  • 2,415
  • 5
  • 18
  • 22