getting a class attribute using a keyword argument

John Hsu john.hsu at clear.net.nz
Wed Jan 19 18:01:25 EST 2005


Guy Robinson wrote:

> Hello,
> 
> I have a list of class instances. I wish to get the appropriate class 
> attribute in each class instance depending on a SINGLE keyword in the 
> calling class.
> 
> How do I get the calling method to correctly recognise the keyword as a 
> keyword and not a class attribute? See example code below (which doesn't 
> work).
> 
> class tocall:
>     def __init__(self):
>         self.title = "test"
>     self.name = "name"
> 
> def callingmethod(self,**kw):
>     for key in kw:
>       if tocall.key == kw[key]:
>            return tocall.key
> 
> which should work as such(but doesn't):
> 
> print callmethod(title = "test")
> print callmethod(name = "name")
> 
> Regards,
> 
> Guy

Hi,

This may be more like you want.

class tocall:
     def __init__(self):
         self.title = "test"
         self.name = "name"

def callmethod(**kw):
     for key in kw:
       if hasattr(tocall(), key):
             return getattr(tocall(), key)

print callmethod(title = "test")
print callmethod(name = "name")




More information about the Python-list mailing list