我正在编写一个装饰器,并且出于各种恼人的原因[0],检查它包装的函数是独立定义还是作为类的一部分定义(以及新类继承哪些类)是有利的. .
例如:
def my_decorator(f):
defined_in_class = ??
print "%r: %s" %(f, defined_in_class)
@my_decorator
def foo(): pass
class Bar(object):
@my_decorator
def bar(self): pass
Run Code Online (Sandbox Code Playgroud)
应打印:
<function foo …>: False
<function bar …>: True
Run Code Online (Sandbox Code Playgroud)
另外,请注意:
typeof或inspect)将不起作用.[0]:具体来说,我正在编写一个装饰器,可以很容易地进行参数化测试nose.然而,nose将不会运行的子类测试发生器unittest.TestCase,所以我想我的装饰器能够确定它是否正在使用的一个子类中,TestCase并且不能用一个适当的错误.显而易见的解决方案-利用isinstance(self, TestCase)调用包装的函数之前是不行的,因为包装的功能需要是一个发生器,它没有得到执行,在所有.
我正在研究是否可以在python中实现一个简单的回调功能.我以为我可能会使用weakref.WeakSet,但显然有一些我遗漏或被误解的东西.正如您在代码中看到的那样,我首先尝试使用"ClassA"对象中的回调方法列表,但意识到这会将已添加到回调列表中的对象保持活动状态.相反,我尝试使用weakref.WeakSet,但也没有做到这一点(至少不是这样).最后四行代码中的注释解释了我想要发生的事情.
谁能帮我这个?
from weakref import WeakSet
class ClassA:
def __init__(self):
#self.destroyCallback=[]
self.destroyCallback=WeakSet()
def __del__(self):
print('ClassA object %d is being destroyed' %id(self))
for f in self.destroyCallback:
f(self)
class ClassB:
def destroyedObjectListener(self,obj):
print('ClassB object %d is called because obj %d is being destroyed'%(id(self),id(obj)))
a1=ClassA()
a2=ClassA()
b=ClassB()
a1.destroyCallback.add(b.destroyedObjectListener)
#a1.destroyCallback.append(b.destroyedObjectListener)
print('destroyCallback len() of obj: %d is: %d'%(id(a1),len(a1.destroyCallback))) # should be 1
a2.destroyCallback.add(b.destroyedObjectListener)
#a2.destroyCallback.append(b.destroyedObjectListener)
print('destroyCallback len() of obj: %d is: %d'%(id(a2),len(a2.destroyCallback))) # should be 1
del a1 # Should call b.destroyedObjectListener(self) in its __del__ method …Run Code Online (Sandbox Code Playgroud) 有这个代码:
>>> class Foo:
... zope.interface.implements(IFoo)
...
... def __init__(self, x=None):
... self.x = x
...
... def bar(self, q, r=None):
... return q, r, self.x
...
... def __repr__(self):
... return "Foo(%s)" % self.x
Run Code Online (Sandbox Code Playgroud)
Obviously, the call of zope.interface.implements in some way alters the properties and behavior of the class Foo.
How does this happen? How do I use this approach in my code?
Example code is the part of zope.interface module.