裝飾器的使用例子
阿新 • • 發佈:2019-01-11
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)