我正在尝试在 Python 中干净地实现 Objective-C 的类别,并找到了我的类似问题的答案。我复制了下面的代码:
类别.py
class category(object):
def __init__(self, mainModule, override = True):
self.mainModule = mainModule
self.override = override
def __call__(self, function):
if self.override or function.__name__ not in dir(self.mainModule):
setattr(self.mainModule, function.__name__, function)
但我不想浪费命名空间。通过使用这个“类别”,还有一个变量作为 NoneType 对象,如下所示:
>>> from categories import category
>>> class Test(object):
... pass
...
>>> @category(Test)
... def foobar(self, msg):
... print msg
...
>>> test = Test()
>>> test.foobar('hello world')
hello world
>>> type(foobar)
<type 'NoneType'>
>>>
我希望它像下面
>>> from categories import category
>>> class Test(object):
... pass
...
>>> @category(Test)
... def foobar(self, msg):
... print msg
...
>>> test = Test()
>>> test.foobar('hello world')
hello world
>>> type(foobar)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'foobar' is not defined
>>>
有没有像下面这样自动删除它?
def __call__(self, function):
if self.override or function.__name__ not in dir(self.mainModule):
setattr(self.mainModule, function.__name__, function)
del(somewhere.function.__name__)
我发现这sys._getframe
给了我一些有用的信息。但我一个人做不到。