pythonsimplexmlrpcserver

Why do I get an AttributeError on getattr in my execute method?


The code below is used as part of a SimpleXMLRPCServer to receive commands from a Java client I've written. The Java client will just call this execute function and pass in a function name from the CameraAssembler class.

from nsCamera.CameraAssembler import CameraAssembler
class MyFunctions:
    ca = None
    def initialize(self):
        # Create Camera object
        self.ca = CameraAssembler(commname=COMM, boardname=BOARD, sensorname=SENSOR, verbose=True)
        return True
    def execute(self, code):
        func = getattr(self.ca,code)
        output = func()
        return output

myfuncs = MyFunctions()
myfuncs.initialize()
output = myfuncs.execute('arm()')
print(output)

Output:

Traceback (most recent call last):
  File "pyTestServer.py", line 31, in <module>
    output = myfuncs.execute("arm()")
  File "pyTestServer.py", line 21, in execute
    func = getattr(MyFunctions.ca,code)
AttributeError: CameraAssembler instance has no attribute 'arm()'

Solution

  • Your parentheses are in the wrong place. The attribute is not called arm(), it's called arm; you need to call the result of getting that attribute.

    output = myfuncs.execute('arm')()
    

    (Note, this code isn't particularly idiomatic. In particular, I can't see why you're setting ca as a class attribute, rather than an instance one. Also, initialisation usually goes in an __init__ method, which is called automatically on instantiation.)