获取函数内部函数的参考,以便在原型/创建函数中使用

时间:2016-09-13 12:46:24

标签: python

我有两个嵌套函数:外部创建一个创建方法/原型,内部将创建该原型的具体示例:

class Example:
    def __init__(self, str):
        self.str = str

def make_prototype(proto_name):
    def make_example(example_name):
        return Example(proto_name + ' ' + example_name)
    return make_example

proto = make_prototype('Prototype 1')
ex1 = proto('Example 1')

现在,我想记住Example中使用的创建函数。我是通过以下方式做到的:

class Example:

    def __init__(self, str, proto):
        self.str = str
        self.proto = proto

def make_prototype(proto_name):
    class make_example:
        def __call__(self, example_name):
            return Example(proto_name + ' ' + example_name, self)
    return make_example()

proto = make_prototype('Prototype 1')
ex1 = proto('Example 1')
ex2 = ex1.proto('Example 2')

我认为这是一个相对优雅且易于理解的解决方案。但是如果没有嵌套的class make_example,有没有办法做到这一点?是否有办法在第一个版本中执行此操作并直接在make_example内获取对函数make_example的引用?类似的东西:

class Example:
    def __init__(self, str, proto):
        self.str = str
        self.proto = proto

def make_prototype(proto_name):
    def make_example(example_name):
        return Example(proto_name + ' ' + example_name, REFERENCE TO THIS FUNC)
    return make_example

proto = make_prototype('Prototype 1')
ex1 = proto('Example 1')
ex2 = ex1.proto('Example 2')

1 个答案:

答案 0 :(得分:1)

您可以使用__call__类方法。你的例子看起来像这样:

class Example:
    def __init__(self, str, proto):
        self.str = str
        self.proto = proto

class MakePrototype():
    def __init__(self, name):
        self.name = name

    def __call__(self, proto_name):
        return Example(proto_name, self)



proto = MakePrototype('Prototype 1')
ex1 = proto('Example 1')
ex2 = ex1.proto('Example 2')