首页 / PYTHON / Python中的类,方法和多态
Python中的类,方法和多态
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Python中的类,方法和多态,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1626字,纯文字阅读大概需要3分钟。
内容图文
我制作了一个模块原型,目的是在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中使用.
内容总结
以上是互联网集市为您收集整理的Python中的类,方法和多态全部内容,希望文章能够帮你解决Python中的类,方法和多态所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。