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

2024-06-17 13:29:30 发布

您现在位置: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')

Tags: 函数nameselfmakereturninitexampledef
1条回答
网友
1楼 · 发布于 2024-06-17 13:29:30

您可以使用__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')

相关问题 更多 >