我制作了一个模块原型,目的是在python中构建复杂的计时器计划.类原型模拟Timer对象,每个对象具有等待时间,重复对Timer和其他Repeat对象进行分组的对象,以及Schedule类,仅用于保存整个构造或Timers和Repeat实例.建筑可以根据需要复杂化,并且需要灵活.
这三个类中的每一个都有一个.run()方法,允许完成整个计划.无论是什么类,.run()方法要么运行计时器,要么运行一定数量的迭代重复组,要么运行计划.
这种面向多态的方法听起来还是愚蠢的?我应该考虑采用哪些其他适当的方法来构建这样一个多功能的实用程序,它允许将所有构建块放在一起,并且简单易用?
谢谢!
这是模块代码:
#####################
## Importing modules
from time import time, sleep
#####################
## Class definitions
class Timer:
"""
Timer object with duration.
"""
def __init__(self, duration):
self.duration = duration
def run(self):
print "Waiting for %i seconds" % self.duration
wait(self.duration)
chime()
class Repeat:
"""
Repeat grouped objects for a certain number of repetitions.
"""
def __init__(self, objects=[], rep=1):
self.rep = rep
self.objects = objects
def run(self):
print "Repeating group for %i times" % self.rep
for i in xrange(self.rep):
for group in self.objects:
group.run()
class Schedule:
"""
Groups of timers and repetitions. Maybe redundant with class Repeat.
"""
def __init__(self, schedule=[]):
self.schedule = schedule
def run(self):
for group in self.schedule:
group.run()
########################
## Function definitions
def wait(duration):
"""
Wait a certain number of seconds.
"""
time_end = time() + float(duration) #uncoment for minutes# * 60
time_diff = time_end - time()
while time_diff > 0:
sleep(1)
time_diff = time_end - time()
def chime():
print "Ding!"
解决方法:
这称为duck typing,它一直在Python中使用.