首页 > 其他 > 详细

装饰器的使用例子

时间:2019-01-11 19:46:06      阅读:233      评论:0      收藏: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)

装饰器的使用例子

原文:https://www.cnblogs.com/likePython/p/10256819.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!