装饰器的使用例子

Posted on 2019-01-11 19:06  return归来  阅读(292)  评论(0)    收藏  举报

1. 在类中的使用

class Vector():
    def __init__(self,outList):
        self.innerList = outList
    def __len__(self):
        return len(self.innerList)
    def __str__(self):
        return "("+",".join(map(str,self.innerList))+")"

    def checkLength(f):
        def wrapper(self,other):
            if len(self) != len(other):
                raise ValueError
            return f(self,other)
        return wrapper

    @checkLength    #add=check(add)
    def add(self,anotherVector):
        return [i+j for i,j in zip(self.innerList,anotherVector.innerList)]
    @checkLength
    def subtract(self,anotherVector):
        return [i-j for i,j in zip(self.innerList,anotherVector.innerList)]
    @checkLength
    def dot(self,anotherVector):
        return sum([i*j for i,j in zip(self.innerList,anotherVector.innerList)])
    def norm(self):
        return math.sqrt(sum([i**2 for i in self.innerList]))
    def equals(self,anotherVector):
        return sorted(self.innerList) == sorted(anotherVector.innerList)