Reputation: 73
Further to my previously question that has helpfully answered, a new related question is:
How can I 'append' a user inputted transcendental function onto a math. prefix (math.user_fn) that python can than work with in the usual manner? Sorry being beginner, I'm not sure of the precise terminology I shot be using, but I think I'm asking how to change object type in this case? e.g.
v1 = input("Type a transcendental function e.g. 'sin' or 'exp': ")
so that I can then compute something like:
math.v1(2.3)
Upvotes: 1
Views: 47
Reputation: 160407
You can't do it in the usual way (i.e dot access). You can get it and call it on the spot with getattr
. The fact is that math.v1
will perform a __getattribute__
call on the module object and look for an attribute who's name isn't the value of v1
but, rather, the string 'v1'
itself.
That fails and there's no means to change it.
You should just opt for getattr
, this supports dynamic attribute fetching:
getattr(math, v1)(2.3)
this attempts to grab an attribute whos' name equals the value of v1
and then calls it on the spot. It's a shorter version for:
func = getattr(math, v1)
func(2.3)
Upvotes: 1