3

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?

4

2 に答える 2

1

私があなたを正しく理解していれば、オブジェクトのメソッドを呼び出したいと思っていますが、メソッドを事前に知らず、文字列に入れているだけです。あれは正しいですか?

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()

あなたはisRunningの中にいます

クラスをいわゆる新しいスタイルのクラスにするためにServerクラスを継承させ、それが引数を取得することに注意してください。これは、これがインスタンスメソッドであるべきであることをpythonに伝えます。バインドされた関数への参照を取得し、それを呼び出します。objectisRunningselfmy_server.__getattribute__my_server.isRunning

次のようなこともできます。

function_map = {
    'check_if_running': my_server.isRunning
}
cmd_str = 'check_if_running'
my_function = function_map[cmd_str]
my_function()

そのため、コマンド文字列が呼び出されるのとまったく同じように関数に名前を付ける必要はありません (Python では、メソッドの命名規則は一般にlike_thisであり、 ではありませんlikeThis) 。

于 2012-05-14T14:47:28.933 に答える
0

私がそれを正しく理解していれば、必要なのは、メソッド自体への参照ではなく、文字列に名前しかないメソッドを呼び出すことです。

getattr関数を使用して、呼び出したいメソッドへの参照を取得できます。

あなたの例でそれを使用する:

cmdStr = "isRunning" 
func = getattr(Server, cmdStr)
test = func()
于 2012-06-09T13:23:51.757 に答える