如何在类中调用外部函数 - python

时间:2013-02-07 17:44:06

标签: python sockets inheritance socketserver

我正在尝试收集通过套接字解析的数据。这是我的代码:

import pickle
import SocketServer

class SocketReciever(SocketServer.BaseRequestHandler):

    def handle(self):
        sint = self.request.makefile('rb')
        objectt = pickle.load(sint)
        #print(objectt)
        ParentClassCall(objectt)

if __name__ == "__main__":
    HOST, PORT = "localhost", 60

    # Create the server, binding to localhost on port 9999
    server = SocketServer.TCPServer((HOST, PORT), SocketReciever)
    # Activate the server; this will keep running until you
    # interrupt the program with Ctrl-C
    server.serve_forever()

data=[]
def ParentClassCall(currentdata):
    data.append(currentdata)

我的问题是如何在SocketReciever类中调用ParentClassCall函数?

我知道这种方法存在安全问题,但它将在没有互联网访问权限的计算机上运行。

2 个答案:

答案 0 :(得分:2)

Python永远不会定义ParentClassCall(),因为它停在server.serve_forever()行。在主要节之前定义函数。

答案 1 :(得分:1)

以下是您的示例的简化版本,以演示此问题:

class Foo(object):

  def __init__(self):
    pass

  def do_something(self):
    not_yet_defined_function()

if __name__ == "__main__":
  foo = Foo()
  foo.do_something()

def not_yet_defined_function():
  print "It worked!"

结果是一样的:

Traceback (most recent call last):
  File "tmp.py", line 11, in <module>
    foo.do_something()
  File "tmp.py", line 7, in do_something
    not_yet_defined_function()

问题是您在定义之前尝试访问该功能。 python解释器按顺序读取文件,按顺序执行命令。 classdef关键字只是创建(类和函数)对象的命令。因此,您需要确保在开始使用它们之前定义所有对象。

通过更改示例来首先定义函数:

class Foo(object):

  def __init__(self):
    pass

  def do_something(self):
    not_yet_defined_function()

def not_yet_defined_function():
  print "It worked!"

if __name__ == "__main__":
  foo = Foo()
  foo.do_something()

然后你得到你想要的结果:

lap:~$ python tmp2.py
It worked!