Import Question ..
Steve
lonetwin at gmail.com
Mon Jul 12 08:45:24 EDT 2004
Hi Vinod,
> This is quite frustrating if i have lots of definitions. So is there a way where i could get something like:
>
> def dosomething(something):
>
> str = something+CommonPart # something is passed as a string
> listdef = def.str
>
> basically i am asking if i can pass the string value to get an attribute from the def file. I
> tried doing something like in the above case, but it returns and tells me def has no
> attribute str.
of course 'def' does not have an attribute called 'str' since you
haven't defined any variable/function/class ..etc called 'str' in
def.py.
However, you can use the builtin getattr() to do what you want to:
----------------------------------------------------------------------------------
>>> print getattr.__doc__
getattr(object, name[, default]) -> value
Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.
When a default argument is given, it is returned when the attribute doesn't
exist; without it, an exception is raised in that case.
----------------------------------------------------------------------------------
so you could do something like:
----------------------------------------------------------------------------------
def dosomething(something):
import def
s = something+CommonPart # something is passed as a string
listdef = getattr(def, s)
----------------------------------------------------------------------------------
HTH
Steve
More information about the Python-list
mailing list