class Pizza(object):def __init__(self):self.toppings = []
def __call__(self, topping):# When using '@instance_of_pizza' before a function definition# the function gets passed onto 'topping'.self.toppings.append(topping())
def __repr__(self):return str(self.toppings)
pizza = Pizza()
@pizzadef cheese():return 'cheese'@pizzadef sauce():return 'sauce'
print pizza# ['cheese', 'sauce']
class Mat(list):def __matmul__(self, B):A = selfreturn Mat([[sum(A[i][k]*B[k][j] for k in range(len(B)))for j in range(len(B[0])) ] for i in range(len(A))])
A = Mat([[1,3],[7,5]])B = Mat([[6,8],[4,2]])
print(A @ B)
>>> m = matrix([1,2,3])>>> m @= m.TTraceback (most recent call last):File "<stdin>", line 1, in <module>TypeError: In-place matrix multiplication is not (yet) supported. Use 'a = a @ b' instead of 'a @= b'.
当它实现时,我希望结果看起来像这样:
>>> m = matrix([1,2,3])>>> m @= m.T>>> mmatrix([[14]])
class WithoutDecorators:def some_static_method():print("this is static method")some_static_method = staticmethod(some_static_method)
def some_class_method(cls):print("this is class method")some_class_method = classmethod(some_class_method)
如果装饰器语法用于相同的目的,则代码更短且更易于理解:
class WithDecorators:@staticmethoddef some_static_method():print("this is static method")
@classmethoddef some_class_method(cls):print("this is class method")
def mydecorator(function):def wrapped(*args, **kwargs):# do some stuff before the original# function gets calledresult = function(*args, **kwargs)# do some stuff after function call and# return the resultreturn result# return wrapper as a decorated functionreturn wrapped
class DecoratorAsClass:def __init__(self, function):self.function = function
def __call__(self, *args, **kwargs):# do some stuff before the original# function gets calledresult = self.function(*args, **kwargs)# do some stuff after function call and# return the resultreturn result
def repeat(number=3):"""Cause decorated function to be repeated a number of times.
Last value of original function call is returned as a result:param number: number of repetitions, 3 if not specified"""def actual_decorator(function):def wrapper(*args, **kwargs):result = Nonefor _ in range(number):result = function(*args, **kwargs)return resultreturn wrapperreturn actual_decorator
def function_decorator(func):def wrapped_func():# Do something before the function is executedfunc()# Do something after the function has been executedreturn wrapped_func