Một trường hợp sử dụng tôi có thể nghĩ là nếu bạn muốn bọc tất cả các phương thức của một lớp với một trang trí hàm. Giả sử bạn có các trang trí sau:
def logit(f):
def res(*args, **kwargs):
print "Calling %s" % f.__name__
return f(*args, **kwargs)
return res
Và các lớp sau:
>>> class Pointless:
def foo(self): print 'foo'
def bar(self): print 'bar'
def baz(self): print 'baz'
>>> p = Pointless()
>>> p.foo(); p.bar(); p.baz()
foo
bar
baz
Bạn có thể trang trí tất cả các phương pháp:
>>> class Pointless:
@logit
def foo(self): print 'foo'
@logit
def bar(self): print 'bar'
@logit
def baz(self): print 'baz'
>>> p = Pointless()
>>> p.foo(); p.bar(); p.baz()
Calling foo
foo
Calling bar
bar
Calling baz
baz
Nhưng đó là LAME! Thay vào đó bạn có thể làm điều này:
>>> def logall(cls):
for a in dir(cls):
if callable(getattr(cls, a)):
setattr(cls, a, logit(getattr(cls, a)))
return cls
>>> @logall
class Pointless:
def foo(self): print 'foo'
def bar(self): print 'bar'
def baz(self): print 'baz'
>>> p = Pointless()
>>> p.foo(); p.bar(); p.baz()
Calling foo
foo
Calling bar
bar
Calling baz
baz
UPDATE: Một phiên bản chung chung hơn của logall
:
>>> def wrapall(method):
def dec(cls):
for a in dir(cls):
if callable(getattr(cls, a)):
setattr(cls, a, method(getattr(cls, a)))
return cls
return dec
>>> @wrapall(logit)
class Pointless:
def foo(self): print 'foo'
def bar(self): print 'bar'
def baz(self): print 'baz'
>>> p = Pointless()
>>> p.foo(); p.bar(); p.baz()
Calling foo
foo
Calling bar
bar
Calling baz
baz
>>>
Họ và tiết lộ: Tôi chưa bao giờ phải làm điều này và tôi chỉ cần thực hiện ví dụ này lên.
@Manoj, vui vì bạn thích nó, tx đã cho tôi biết! –