Reputation: 59
I'm new to python. I'm using python 3.1.2 I've to communicate to the xml-rpc server through my code. From my code, I'm calling the client.py that will in-turn connect to the server to get the lists of comments from the server.
The working code:
class xmlrpc:
def connect(self, webaddr):
self.server = ServerProxy(webaddr)
Listing the method:-
my_list = self.server.tests.getTests()
the above method is working, but, whereas i've constraint to set the tests.getTests()
into a single cmd_str
like below
my_list = self.server.cmd_str
in this case, cmd_str
sent to the client.py as a string itself and not like other one. Could anyone pls help me how to acheive this?
Upvotes: 3
Views: 320
Reputation: 4667
If I understood it right, what you need is to call a method which you have only the name in a string, not a reference to the method itself.
You could use the getattr function to get a reference to the method you want to call.
Using it in your example:
cmdStr = "isRunning"
func = getattr(Server, cmdStr)
test = func()
Upvotes: 0
Reputation: 8509
If I understand you right, you want to call a method of an object, but you don't know the method in advance, you just have it in a string. Is that correct?
class Server(object):
def isRunning(self):
print("you are inside the isRunning")
my_server = Server()
cmd_str = "isRunning"
my_function = my_server.__getattribute__(cmd_str)
my_function()
you are inside the isRunning
Note that I let the Server
class inherit from object
to make it a so-called new-style class, and that isRunning
gets an argument self
, which tells python that this should be an instance method. my_server.__getattribute__
will get a reference to the bound function my_server.isRunning
, which you then call.
You could also do something like this:
function_map = {
'check_if_running': my_server.isRunning
}
cmd_str = 'check_if_running'
my_function = function_map[cmd_str]
my_function()
so you don't have to name your functions exactly the way that your command strings are called (in python, the naming convention for methods is generally like_this
, not likeThis
)
Upvotes: 1