我在Python中試圖乾淨的Objective-C的類的實現,並發現this answer類似的問題。我複製下面的代碼:如何知道調用方法的位置?
categories.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
給了我一些有用的信息。但我自己無法做到。
謝謝你給我一個答案。我會改變我的計劃,並以更加pythonic的方式實施它們! – user2100702 2013-03-06 14:43:23