在 class 之外的 python 模块中访问函数

access function in python module outside of class

我有下一个情况。我尝试覆盖 BaseHTTPServer.py 文件中 BaseHTTPRequestHandler 中的方法 send_error。 BaseHTTPServer.py 关于 send_error 方法有这样的结构:

def _quote_html(html):
    blah
    blah

class HTTPServer():
    blah
    blah
class BaseHTTPRequestHandler():
    blah
    blah
    def send_error(self):
        blah
        blah
        content = (self.error_message_format %
                {'code': code, 'message': _quote_html(message), 'explain': explain})

这里在send_error方法里面调用了_quote_html函数。它在 BaseHTTPServer.py 文件中工作,但如果创建我自己的 httphandler,继承自 BaseHTTPRequestHandler 并尝试覆盖 send_error,我的函数 send_error 无法访问位于 [=21] 中的 _quote_html 函数=] BaseHTTPRequestHandler 之外的文件 class:

Traceback (most recent call last):
  File "/usr/lib/python2.7/SocketServer.py", line 593, in process_request_thread
    self.finish_request(request, client_address)
  File "/usr/lib/python2.7/SocketServer.py", line 334, in finish_request
    self.RequestHandlerClass(request, client_address, self)
  File "/python_codes/Junior/Level1/C&C/HttpServer/HttpHandler.py", line 12, in __init__
    BaseHTTPRequestHandler.__init__(self, *args, **kwargs)
  File "/usr/lib/python2.7/SocketServer.py", line 649, in __init__
    self.handle()
  File "/usr/lib/python2.7/BaseHTTPServer.py", line 340, in handle
    self.handle_one_request()
  File "/python_codes/Junior/Level1/C&C/HttpServer/HttpHandler.py", line 26, in handle_one_request
    if not self.parse_request():
  File "/usr/lib/python2.7/BaseHTTPServer.py", line 286, in parse_request
    self.send_error(400, "Bad request syntax (%r)" % requestline)
  File "/python_codes/Junior/Level1/C&C/HttpServer/HttpHandler.py", line 106, in send_error
    {'code': code, 'message': _quote_html(message), 'explain': explain})
NameError: global name '_quote_html' is not defined 

所以我的问题是如何访问模块文件中父 class 之外的函数?在我的例子中,从 send_error() 到 _quote_html()。一切都是从 BaseHTTPServer.py:

导入的
from BaseHTTPServer import *

将您的函数重命名为 quote_html。或者像这样进行显式导入:

from BaseHTTPServer import _quote_html

开始于:

from M import * does not import objects whose name starts with an underscore.

我已经试过了,效果很好:

def b():
    return 45
class Person(object):

    def getYears(self):
        return self.b()

print Person().getYears()

所以,我看到的唯一区别是括号之间的 'objects'。