鱼C论坛

 找回密码
 立即注册
查看: 2329|回复: 4

问题求助@@@

[复制链接]
发表于 2016-2-21 19:10:12 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
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):
            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")

---------------------------
我的问题是func 到底是什么呀!
>>> a = MyTimer(2+3)
>>> a.timing()
Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    a.timing()
  File "D:\Python exercise\044魔法方法.简单定制.py", line 194, in timing
    self.func()
TypeError: 'int' object is not callable
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2016-2-21 19:17:47 | 显示全部楼层
前面 __init__ 里面func就是一个变量,你换成a也是一样的
后面timing函数里面
  1. self.func()
复制代码

你确定没打错?
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2016-2-21 19:52:03 | 显示全部楼层
shuofxz 发表于 2016-2-21 19:17
前面 __init__ 里面func就是一个变量,你换成a也是一样的
后面timing函数里面

我是复制,确实没错
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2016-2-21 20:28:08 | 显示全部楼层
实例化MyTimer时func参数需要是函数名

比如
  1. def fun():
  2.     for a in range(10000):
  3.         pass

  4. a = MyTimer(fun)
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2016-2-21 22:53:57 | 显示全部楼层
kunaiai 发表于 2016-2-21 20:28
实例化MyTimer时func参数需要是函数名

比如

恩恩 我明白了,谢啦^_^
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2026-2-19 18:56

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表