【发布时间】:2013-07-23 13:12:10
【问题描述】:
我有以下代码:
import threading
from functools import wraps
class Synchronized(object):
def __init__(self):
self.lock = threading.Lock()
def synchronized(f):
@wraps(f)
def wrapper(self, *args, **kwargs):
with self.lock:
print "here"
return f(self, *args, **kwargs)
return wrapper
@synchronized
def go(self):
print 1
class B(Synchronized):
@synchronized
def foo(self):
return 1
此代码在导入抱怨时失败:
File "a.py", line XXX, in B
@synchronized
NameError: name 'synchronized' is not defined
但是,如果我注释掉 B 并只使用 Syncrhonized().go(),它会很好用。
问题: python 如何知道基类中的 @synchronized 是什么,但无法在其派生类中解析它?
【问题讨论】:
-
为什么要同步成为一个方法,而不是一个函数?
-
因为我想将它保留在类中以便更好地组织代码
标签: python decorator python-decorators