Normal way:
import ham
ham.eggs.my_func()
ham.sausage.my_func()
How I want it “Dynamic” way:
str = 'eggs'
ham.str.my_func()
str = 'sausage'
ham.str.my_funct()
Same thing, but ideally how I would use it in a loop:
for x in ['eggs', 'sausage']
ham.x.my_func()
Basically, I want a string tell which class’s my_func to invoke?
This gets the method/thing (Python is duck typed) from
hamwhich was assigned as an attribute whose name was the contents ofx(ifxis'foo', then it’ll beham.foo), then invokesmy_funcon thatIf
hamhas no method with the right name, you’ll get an exception.Incidentally, your example of
ham.str.my_func()should begetattr(ham, str).my_func().If you want to really do this the right way, you could use the
impmethod to only get members of a certain type, or use additional introspection.