考虑这个小例子:
import datetime as dt
class Timed(object):
def __init__(self, f):
self.func = f
def __call__(self, *args, **kwargs):
start = dt.datetime.now()
ret = self.func(*args, **kwargs)
time = dt.datetime.now() - start
ret["time"] = time
return ret
class Test(object):
def __init__(self):
super(Test, self).__init__()
@Timed
def decorated(self, *args, **kwargs):
print(self)
print(args)
print(kwargs)
return dict()
def call_deco(self):
self.decorated("Hello", world="World")
if __name__ == "__main__":
t = Test()
ret = t.call_deco()
Run Code Online (Sandbox Code Playgroud)
打印
Hello
()
{'world': 'World'}
Run Code Online (Sandbox Code Playgroud)
为什么self参数(应该是Test obj实例)不作为第一个参数传递给装饰函数decorated?
如果我手动完成,例如:
def call_deco(self):
self.decorated(self, "Hello", …Run Code Online (Sandbox Code Playgroud) 假设我们有一个类'Parent',由于某种原因已__new__定义,并且继承了它的类'Child'.(在我的情况下,我试图继承我无法修改的第三方课程)
class Parent:
def __new__(cls, arg):
# ... something important is done here with arg
Run Code Online (Sandbox Code Playgroud)
我的尝试是:
class Child(Parent):
def __init__(self, myArg, argForSuperclass):
Parent.__new__(argForSuperclass)
self.field = myArg
Run Code Online (Sandbox Code Playgroud)
但同时
p = Parent("argForSuperclass")
Run Code Online (Sandbox Code Playgroud)
按预期工作
c = Child("myArg", "argForSuperclass")
Run Code Online (Sandbox Code Playgroud)
失败,因为'Child'试图调用__new__它从'Parent'而不是它自己的__init__方法继承的方法.
为了获得预期的行为,我必须在"儿童"中进行哪些更改?
最近,StackOverflow社区帮助我开发了一个相当简洁的@memoize装饰器,它不仅能够以一般方式装饰函数,还能够装饰方法和类,即,无需预先知道它将装饰什么类型的东西.
我遇到的一个问题是,如果你用一个类装饰一个类@memoize,然后尝试用它来装饰其中一个方法@staticmethod,这将无法按预期工作,即你根本无法调用ClassName.thestaticmethod().我提出的原始解决方案看起来像这样:
def memoize(obj):
"""General-purpose cache for classes, methods, and functions."""
cache = obj.cache = {}
def memoizer(*args, **kwargs):
"""Do cache lookups and populate the cache in the case of misses."""
key = args[0] if len(args) is 1 else args
if key not in cache:
cache[key] = obj(*args, **kwargs)
return cache[key]
# Make the memoizer func masquerade as the object we are memoizing.
# This makes class attributes and static methods behave …Run Code Online (Sandbox Code Playgroud)