__getattr__ related question

Daniel Dittmar daniel.dittmar at sap.com
Wed Dec 12 09:00:52 EST 2001


Use
return getattr (self.component, name)
instead of accessing the class dict.

This will return a 'bound' method where the self parameter is already filled
in.

Daniel

"dominikush" <dominikush at yahoo.com> wrote in message
news:mailman.1008160755.17684.python-list at python.org...
> Dear Pythonics,
>
> the __getattr__ method causes me some headache. To prohibit unwanted
> method calls of an object, I shield it by an interface object. So,
> all method calls are addressed to the interface object. That means
> the user calls
>
>     capsuleInterface.send("Hallo")
>
> instead of directly calling capsule.send("Hallo"), see example
> below. The __getattr__ in Port catches the call and returns the
> send() method of Capsule. However, evaluating the method fails
>
>     >>> capsuleInterface.send("Hallo")
>     Traceback (most recent call last):
>       File "<stdin>", line 1, in ?
>     TypeError: not enough arguments; expected 2, got 1
>
> Clearly, the send() method expects the arguments self and data, but
> self is missing! How do I get it right? How can I add the self value
> (it should be the capsule object) to the parameter list before the
> method retrieved by __getattr__ is evaluated?
>
> Gruss
>
> Dominikus
>
> --- Example ---
>
> class Port:
>     def __init__(self,component):
>         self.component = component
>         self.methods = []
>     def registerMethod(self,methodName):
>         self.methods.append(methodName)
>     def __getattr__(self,name):
>         if name in self.methods:
>             try:
>                 return self.component.__class__.__dict__[name]
>             except KeyError, error:
>                 raise AttributeError, error
>         raise AttributeError, name+" is not known to port"
>
> class CapsuleInterface(Port):
>     pass
>
> class Capsule:
>     def send(self,data):
>         print "Capsule sends",data
>
> capsule = Capsule()
> capsuleInterface = CapsuleInterface(capsule)
> capsuleInterface.registerMethod("send")
>
>





More information about the Python-list mailing list