|
发表于 2016-5-22 21:13:50
|
显示全部楼层
你的__call__(self)中没有参数自动会调用timeslong.call();
- #__init__是初始化,self是一个指针,指代当前的类或者实例化后当前这个实例对象,和javascript
- #中的this或者php中的$this一样。__call__是你要调用的对象,__call__(self)指调用当前的类。
- #你的自定义函数f()只是修饰器中参数的func在另一地方或者位置定义而已,
- #程序执行会去执行@timeslong类,参数func就是f()。其实理解和内嵌函数差不多。
- #我写一下__call__,__add__,__sub__,__str__,__getattr__,__repr__,其他魔法方法类似。
- import time
- def fff():
- print(1111)
- y = 0
- for i in [100,200,300,400,500]:
- y += i + 1
- print(y)
- return y
-
- class timeslong():
- def __init__(self,func):
- self.a = func
- print(self.a)
- def __new__(cls,func):
- print('Nstr 的')
- start = time.clock()
- print('Time start!')
- func()
- print('Time ending')
- end = time.clock()
- print('Used:%s.'% (end - start))
- return Nstr(func)
- class Nstr():
- def __init__(self,func,numlist = ['a','b','c']):
- self.nstr = func()
- self.change(self.nstr)
- self.numlist = numlist
- def __call__(self,num):
- return self.numlist[num]
- def change(self,value):
- if isinstance(value,str):
- for i in value:
- self.nstr += ord(i)
- elif isinstance(value,(int,float)):
- self.nstr = value
- return self.nstr
- def __str__(self):
- return '你好,等于' + str(self.nstr)
-
- def __add__(self,other):
- if type(other) == type(self):
- return self.nstr+other.nstr
- else:
- return self.nstr+other
- def __radd__(self,other):
- if type(other) == type(self):
- return other.__add__(self)
- else:
- return other + self.nstr
- def __sub__(self,other):
- if type(other) == type(self):
- return other.nstr - self.nstr
- else:
- return other - self.nstr
- def __rsub__(self,other):
- if type(other) == type(self):
- return other.__sub__(self)
- else:
- return other - self.nstr
- def __mul__(self,other):
- if type(other) == type(self):
- return self.nstr*other.nstr
- else:
- return self.nstr*other
- def __rmul__(self,other):
- if type(other) == type(self):
- return other.__mul__(self)
- else:
- return other * self.nstr
- def __truediv__(self,other):
- if type(other) == type(self):
- return self.nstr/other.nstr
- else:
- return self.nstr/other
- def __rtruediv__(self,other):
- if type(other) == type(self):
- return other.__truediv__(self)
- else:
- return other / self.nstr
- def __floordiv__(self,other):
- if type(other) == type(self):
- return self.nstr//other.nstr
- else:
- return self.nstr//other
- def __rfloordiv__(self,other):
- if type(other) == type(self):
- return other.__floordiv__(self)
- else:
- return '你好,我没有定义噢'
-
- if __name__ == '__main__':
- @timeslong
- def f():
- print(1111)
- y = 0
- for i in range (10):
- y += i + 1
- print(y)
- return y
- b = f
复制代码
你也可以直接调用b(2)等,会打印'c',代码和图都给你自己试试吧。 |
评分
-
查看全部评分
|