0基础学Python——面向对象-可迭代、面向对象-迭代器、call方法、call方法实现装饰器、计算函数运行时间
面向对象–可迭代
把对象看做容器,存储数据
如果希望对象可用 for–in遍历,把它转换为可迭代对象
实现方法
重写 __iter__方法,返回一个迭代器
class Student:
def __init__(self, hobbys):
self.hobbys = hobbys
def __iter__(self, *args, **kwargs):
return iter(self.hobbys)
stu = Student(['吃饭', '睡觉', '打豆豆'])
for i in stu:
print(i)
for i in stu:
print(i)
面向对象–迭代器
把对象看做容器,存储数据
如果希望对象迭代器
实现方法
重写 __iter__方法,返回当前对象
重写 __next__方法,返回并删除
class Student:
def __init__(self, hobbys):
self.hobbys = hobbys
def __iter__(self):
return self
def __next__(self):
if len(self.hobbys) > 0:
return self.hobbys.pop(0)
raise StopIteration
stu = Student(['吃饭', '睡觉', '打豆豆'])
print(next(stu))
print(next(stu))
print(next(stu))
# print(next(stu))
print('*' * 99)
for i in stu:
print(i)
call方法
作用
__call__: 可以使对象可调用
class Student:
def __init__(self):
print('__init__')
def __call__(self, *args, **kwargs):
print('__call__')
stu = Student() # __init__
stu() # __call__
call方法实现装饰器
代码演示
class Fn:
def __init__(self, func):
self.func = func
def __call__(self, *args, **kwargs):
print('1')
ret = self.func(*args, **kwargs)
print('2')
return ret
@Fn
def fn1(n):
print('hello', n)
fn1('world')
计算函数运行时间
代码演示
import time
def timer(func):
t1 = time.time()
def inner():
func()
t2 = time.time()
return f'{t2 - t1}秒'
return inner
class Time:
def __init__(self, func):
self.func = func
def __call__(self, *args, **kwargs):
t1 = time.time()
ret = self.func()
t2 = time.time()
print(f'{t2 - t1}秒')
return ret
# @Time
@timer
def fn():
for i in range(10000):
print(i)
print(fn())
标签:__,迭代,stu,self,面向对象,call,print,def
From: https://blog.csdn.net/2201_75539182/article/details/143494598