python - 使用对象调用函数?
问题描述
在两者之间编写一个布尔函数,它接受两个
MyTime
对象t1
和t2
,作为参数,如果调用对象介于这两个时间之间,则返回 True 。假设t1 <= t2
,并使测试在下限处关闭并在上限处打开,即如果 ,则返回 Truet1 <= obj < t2
。
现在从这个问题的措辞来看,函数中似乎应该只有两个参数,但我看不到只使用两个参数来制作这样一个函数的方法。我的意思是我猜你可以创建另一个函数来创建一个作为MyTime
对象的变量,但我只想将它保留在一个函数中而不是创建两个。问题的措辞使您看起来应该有Object(Function(t1,t2))
,但我认为这是不可能的。是否可以仅使用两个参数来制作“介于”函数?这是我的代码
class MyTime:
""" Create some time """
def __init__(self,hrs = 0,mins = 0,sec = 0):
"""Splits up whole time into only seconds"""
totalsecs = hrs*3600 + mins*60 + sec
self.hours = totalsecs // 3600
leftoversecs = totalsecs % 3600
self.minutes = leftoversecs // 60
self.seconds = leftoversecs % 60
def __str__(self):
return '{0}:{1}:
{2}'.format(self.hours,self.minutes,self.seconds)
def to_seconds(self):
# converts to only seconds
return (self.hours * 3600) + (self.minutes * 60) + self.seconds
def between(t1,t2,x):
t1seconds = t1.to_seconds()
t2seconds = t2.to_seconds()
xseconds = x.to_seconds()
if t1seconds <= xseconds < t2seconds:
return True
return False
currentTime = MyTime(0,0,0)
doneTime = MyTime(10,3,4)
x = MyTime(2,0,0)
print(between(currentTime,doneTime,x))
解决方案
您是 100% 正确的,它确实需要三个参数。如果你把它写成类的成员函数MyTime
,它会得到第三个参数self
:
class MyTime():
# the guts of the class ...
def between(self, t1, t2):
t1seconds = t1.to_seconds()
t2seconds = t2.to_seconds()
myseconds = self.to_seconds()
return t1seconds <= myseconds < t2seconds
您可以将此方法用于:
currentTime = MyTime(0, 0, 0)
doneTime = MyTime(10, 3, 4)
x = MyTime(2, 0, 0)
x.between(currentTime, doneTime)
self
参数是通过调用类实例的方法自动传入的。
推荐阅读
- ruby - 如何简化 Ruby 中的活动记录查询
- c# - 在启用“编辑并继续”的情况下自动中断/暂停代码编辑
- sql - 在 SQL 中使用不同的条件两次获取同一列
- python - 将 Architect 与 Django 抽象模型类一起使用
- amazon-web-services - 对 EC2 实例的共享访问
- kendo-ui - 在 kendo anutocomplete 中是否有任何替代方法用于绑定 valueField 和 textField
- highcharts - Highcharts 显示问题
- python - Cuda 运行时错误 cudaErrorNoDevice:未检测到支持 CUDA 的设备
- postgresql - PostgreSQL 在表更新时触发事件
- c# - 在哪里清理处置模式中的非托管资源?