我有两个嵌套函数:外部函数创建一个创建方法/原型,内部函数将创建该原型的具体示例:
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')
您可以使用
__call__
类方法。您的示例如下所示:相关问题 更多 >
编程相关推荐