__getattr__ related question

dominikush dominikush at yahoo.com
Wed Dec 12 07:38:28 EST 2001


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