覆盖不在类

时间:2016-02-16 15:17:25

标签: python python-2.7

我有一个函数,我想从另一个文件覆盖而不更改原始文件。我该怎么做?

以下是我的功能示例。

def url_for(path_or_uri, lang=None):
    if isinstance(path_or_uri, unicode):
        path_or_uri = path_or_uri.encode('utf-8')
    current_path = request.httprequest.path
    if isinstance(current_path, unicode):
        current_path = current_path.encode('utf-8')
    location = path_or_uri.strip()
    force_lang = lang is not None
    url = urlparse.urlparse(location)

    if request and not url.netloc and not url.scheme and (url.path or force_lang):
        location = urlparse.urljoin(current_path, location)

        lang = lang or request.context.get('lang')
        langs = [lg[0] for lg in request.website.get_languages()]

        if (len(langs) > 1 or force_lang) and is_multilang_url(location, langs):
            ps = location.split('/')
            if ps[1] in langs:
                # Replace the language only if we explicitly provide a language to url_for
                if force_lang:
                    ps[1] = lang
                # Remove the default language unless it's explicitly provided
                elif ps[1] == request.website.default_lang_code:
                    ps.pop(1)
            # Insert the context language or the provided language
            elif lang != request.website.default_lang_code or force_lang:
                ps.insert(1, lang)
            location = '/'.join(ps)

    return location.decode('utf-8')

1 个答案:

答案 0 :(得分:0)

我想我明白你要做的事情。

如果您想在导入后更改另一个模块中某个功能的定义,您可以像重新分配任何变量一样重新分配该功能。

以下是一个例子:

foo.py

def foo():
    print('Goodbye, World')


def foo_caller():
    foo()

main.py

import foo


def new_foo(var):
    print('Hello, World!')


foo.foo = new_foo

foo.foo()
foo.foo_caller()

如果将这些文件放在命名为指定的文件中并运行main.py,您将看到它使用new_foo代替foo,即使对于该模块中的内部函数调用也是如此。

相关问题