老师这段代码func需要输入什么类型的数据才能运行
import time as tclass MyTimer:
def __init__(self, func, number=1000000):
self.prompt = "未开始计时!"
self.lasted = 0.0
self.default_timer = t.perf_counter
self.func = func 这个func的值我应该输入什么
self.number = number
def __str__(self):
return self.prompt
__repr__ = __str__
def __add__(self, other):
result = self.lasted + other.lasted
prompt = "总共运行了 %0.2f 秒" % result
return prompt
# 内部方法,计算运行时间
def timing(self):
self.begin = self.default_timer()
for i in range(self.number):
print(self.func())
self.func() 这个self.func()是什么作用
self.end = self.default_timer()
self.lasted = self.end - self.begin
self.prompt = "总共运行了 %0.2f 秒" % self.lasted
# 设置计时器(time.perf_counter() 或 time.process_time())
def set_timer(self, timer):
if timer == 'process_time':
self.default_timer = t.process_time
elif timer == 'perf_counter':
self.default_timer = t.perf_counter
else:
print("输入无效,请输入 perf_counter 或 process_time")
t = MyTimer()
谢谢老师的解答
传入一个函数呀 python爱好者. 发表于 2022-3-30 15:15
传入一个函数呀
我传入了3说是不能传入一个int类型,我传入了字符串也不行。列表也不行
python爱好者. 发表于 2022-3-30 15:15
传入一个函数呀
import time as t
class MyTimer:
def __init__(self, func, number=1000000):
self.prompt = "未开始计时!"
self.lasted = 0.0
self.default_timer = t.perf_counter
self.func = func
self.number = number
def __str__(self):
return self.prompt
__repr__ = __str__
def __add__(self, other):
result = self.lasted + other.lasted
prompt = "总共运行了 %0.2f 秒" % result
return prompt
# 内部方法,计算运行时间
def timing(self):
self.begin = self.default_timer()
for i in range(self.number):
print(self.func())
self.func()
self.end = self.default_timer()
self.lasted = self.end - self.begin
self.prompt = "总共运行了 %0.2f 秒" % self.lasted
# 设置计时器(time.perf_counter() 或 time.process_time())
def set_timer(self, timer):
if timer == 'process_time':
self.default_timer = t.process_time
elif timer == 'perf_counter':
self.default_timer = t.perf_counter
else:
print("输入无效,请输入 perf_counter 或 process_time")
t = MyTimer(3,5)
提示============== RESTART: C:\Users\Administrator\Desktop\shijian.py ==============
>>> t.timing()
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
t.timing()
File "C:\Users\Administrator\Desktop\shijian.py", line 25, in timing
print(self.func())
TypeError: 'int' object is not callable
>>> redaiconglin 发表于 2022-3-30 15:20
import time as t
class MyTimer:
你连 func 都没有先传进去,当然报错,应该是:
t = MyTimer(你自己的一个函数) redaiconglin 发表于 2022-3-30 15:20
import time as t
class MyTimer:
老师我看小甲鱼老师的这段代码里面没有设置func的函数。如果要传入这个函数应该怎么传。t.func()吗,我不是很理解。谢谢了
页:
[1]