python - 使用对象调用函数?

标签 python python-3.x object

Write a Boolean function between that takes two MyTime objects, t1 and t2, as arguments, and returns True if the invoking object falls between the two times. Assume t1 <= t2, and make the test closed at the lower bound and open at the upper bound, i.e. return True if t1 <= obj < t2.

现在从这个问题的措辞来看,函数中似乎应该只有两个参数,但我看不出只使用两个参数来创建这样一个函数的方法。我的意思是我想你可以创建另一个函数来创建一个变量,该变量是 MyTime对象,但我只打算将它保留为一个功能而不是两个。问题的措辞让你看起来应该有 Object(Function(t1,t2))但我不认为这是可能的。是否可以只使用两个参数来创建“between”函数?这是我的代码

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 参数是通过调用类实例上的方法自动传入的。

关于python - 使用对象调用函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51353229/

相关文章:

python - Dataflow BigQuery 插入作业因大数据集而立即失败

python - 获得 fastpython protobuf 支持的问题

python - 帮我用 f-string 修复这个代码吗?

javascript - 根据另一个数组中的值删除嵌套对象数组中的值

c# - 在 C# 中,如何在运行时检查对象是否属于某种类型?

javascript - 错误 "document.getElementById(...)' 为 null 或不是对象”

python - Python 中的标志是什么?

python - Django > xhtml2pdf > 让它工作?

python - plotly :如何为子 plotly 标题分配变量?

python - 如何拆分数据框单元格中的数据并在拆分时执行 Pandas groupby?