如何找到metamethod的名称?

2024-04-19 00:30:55 发布

您现在位置:Python中文网/ 问答频道 /正文

考虑以下示例:

import types

methods = ['foo', 'bar']

def metaMethod(self):
    print "method", "<name>"

class Egg:
    def __init__(self):
        for m in methods:
            self.__dict__[m] = types.MethodType(metaMethod, self)

e = Egg()
e.foo()
e.bar()

我应该写什么来代替"<name>",所以输出是

method foo
method bar

Tags: nameimportself示例fooiniteggdef
2条回答

您必须以某种方式传递该参数,所以为什么不让metaMethod返回一个知道要打印什么的函数,而不是直接打印它呢?(我相信还有更多的方法可以做到这一点,这只是一种可能性。)

import types

methods = ['foo', 'bar']

def metaMethod(self, m):
    def f(self):
        print "method", m
    return f

class Egg:
    def __init__(self):
        for m in methods:
            self.__dict__[m] = types.MethodType(metaMethod(self, m), self)

e = Egg()
e.foo()
e.bar()

运行此脚本打印

method foo
method bar

一种方法是使metaMethod成为类而不是函数。你知道吗

class metaMethod:
    def __init__(self, name):
        self.name = name
    def __call__(*args, **kwargs):
        print "method", self.name

相关问题 更多 >