0

I got a class:

class thing:
    def __init__(self, inp, inp2):
        self.aThing = inp
        self.bThing = inp2
    def test(self, character):
        print(self.eval(character+"Thing"))

(Important is the last line)

The test script would look like this:

x = thing(1, 2)
x.test("b")

Trying to run this it screams at me:

AttributeError: 'thing' object has no attribute 'eval'

Makes sense, so I tried this:

print(self.(eval(character+"Thing")))

Now its a Syntax error: .(

So is there a way Í could do this? And if not, is there a way to do this kind of case distinction without having to list all possible cases? (like using if-statements or the switch equivalent)

Oh, and I know that in this case I could just use a dictionary instead of a class, but that is not what I am searching for...

encomiastical
  • 143
  • 13
  • FWIW, using `eval` is rarely a good idea: it's slow and potentially dangerous. You can sometimes get away with it if you aren't going to be evaluating user input, but it's still better to avoid it when possible. And in this situation, `getattr` does exactly what you need, as Sebastian has shown. For more info see [Eval really is dangerous](http://nedbatchelder.com/blog/201206/eval_really_is_dangerous.html) by SO veteran Ned Batchelder. – PM 2Ring Nov 22 '15 at 14:47

1 Answers1

1

Your question is very broad and you're probably better off watching a talk on polymorphism and the super function(behaviour distinction without if) or python design patterns.

For the specific problem you posted you want to use getattr:

getattr(object, name[, default])

Return the value of the named attribute of object. name must be a string. If the string is the name of one of the object’s attributes, the result is the value of that attribute. For example, getattr(x, 'foobar') is equivalent to x.foobar. If the named attribute does not exist, default is returned if provided, otherwise AttributeError is raised.

class thing:
    def __init__(self, inp, inp2):
        self.aThing = inp
        self.bThing = inp2
    def test(self, character):
        print(getattr(self,character+"Thing"))

Example Demo

>>> t = thing(1, 2)
>>> t.test("a")
1
Sebastian Wozny
  • 16,943
  • 7
  • 52
  • 69