简体   繁体   English

python中一个简单的时钟类

[英]A Simple Clock Class in python

Class Clock:   
    def __init__(self):
        self._hours = 12
        self._minutes = 0
        self._seconds = 0

    def getHours(self):
        return self._hours

    def getMinutes(self):
        return self._minutes

    def getSeconds(self):
        return self._seconds

    def show(self):
        print "%d:%02d:%02d" % (self._hours, self._minutes, self._seconds)

I want to add a method to this class called setTime which takes hours, minutes, and seconds as parameters and make appropriate changes to the object's attributes.我想向这个名为 setTime 的类添加一个方法,该方法以小时、分钟和秒为参数,并对对象的属性进行适当的更改。 The following code makes use of this class and the method setTime.下面的代码使用了这个类和 setTime 方法。

clk = Clock()
clk.setTime(12, 34, 2)
print clk.getHours()
clk.show()

    def setTime(self, hours = 12, minutes = 34, seconds = 2):
        self._hours = hours
        self._minutes = minutes
        self._seconds = seconds

My question is whether my setTime method is correct?我的问题是我的 setTime 方法是否正确? Also, how to check whether my function is correct or not?另外,如何检查我的功能是否正确?

You can initialize the time in the class constructor:您可以在类构造函数中初始化时间:

Class Clock:   
    def __init__(self, hours, minutes, seconds):
        self._hours = hours
        self._minutes = minutes
        self._seconds = seconds
....


clk = Clock(12, 34, 2)

It looks correct to me, except for two things.对我来说,它看起来是正确的,除了两件事。 You might want to remove the default values;您可能希望删除默认值; they seem unnecessary.他们似乎没有必要。 You want to range check the values and raise ValueError if they're out of range.您想对值进行范围检查,如果超出范围则引发ValueError

A simple test would be to set the clock to something, then get the data back and check it;一个简单的测试是将时钟设置为某个值,然后取回数据并进行检查; repeat for a few values.重复几个值。 This can be automated;这可以自动化; the doctest module is fairly simple to use. doctest模块使用起来相当简单。

EDIT:编辑:

Here's an example of using doctest .这是使用doctest的示例。 The tests go directly into docstrings anywhere in the module.测试直接进入模块中任何地方的文档字符串。 doctest.testmod() looks for them and tries to run them as if they were interactive sessions. doctest.testmod()寻找它们并尝试运行它们,就好像它们是交互式会话一样。 If the output isn't as expected, it says so.如果输出不符合预期,它会这样说。 If all goes well, there's no output.如果一切顺利,则没有输出。

class Clock:
    """Clock

    Class that acts like a clock.

    For doctest -

    >>> c = Clock()
    >>> c.setTime(23, 59, 59)
    >>> c.show()
    23:59:59
    >>> c.getMinutes()
    59
    >>> c.setTime(0, 0, 0)
    >>> c.show()
    0:00:00

    # No range or type checking yet
    >>> c.setTime(42, 'foo', [1, 2, 3])

    # However, the print will fail
    >>> c.show()
    Traceback (most recent call last):
    ...
    TypeError: int argument required

    # Another kind of error
    >>> c.setTime(foo=42)
    Traceback (most recent call last):
    ...
    TypeError: setTime() got an unexpected keyword argument 'foo'

    """

    def __init__(self):
        self._hours = 12
        self._minutes = 0
        self._seconds = 0

    def getHours(self):
        return self._hours

    def getMinutes(self):
        return self._minutes

    def getSeconds(self):
        return self._seconds

    def show(self):
        print "%d:%02d:%02d" % (self._hours, self._minutes, self._seconds)

    def setTime(self, hours = 12, minutes = 34, seconds = 2):
        self._hours = hours
        self._minutes = minutes
        self._seconds = seconds

if __name__ == '__main__':
    import doctest
    doctest.testmod()

Your setTime method is correct, however it seems odd to be setting the default hours, minutes, and seconds to such arbitrary numbers.您的setTime方法是正确的,但是将默认的小时、分钟和秒设置为这样的任意数字似乎很奇怪。 Perhaps hours = 12, minutes = 0, and seconds = 0 would make more sense?也许小时 = 12、分钟 = 0 和秒 = 0 会更有意义? Perhaps even doing away with the default values altogether is best.也许甚至完全取消默认值是最好的。

You don't have any validation -- what if someone uses your class and accidentally sets the hours to 29?您没有任何验证——如果有人使用您的课程并且不小心将小时数设置为 29 怎么办?

Finally, as I mentioned in my comment, you can test your function by trying it out.最后,正如我在评论中提到的,您可以通过尝试来测试您的功能。 Does it do the right thing in the simple case?在简单的情况下它做正确的事吗? Does it do the right thing with default values?它使用默认值做正确的事情吗? What happens if you toss in negative seconds?如果你在负秒内抛球会发生什么? What do you want to happen?你想发生什么? These are all things you should consider when testing a method or class -- does it work in the intended case, and does it work in all the exceptional/corner cases.这些都是您在测试方法或类时应该考虑的所有事情——它是否适用于预期的情况,以及它是否适用于所有特殊/极端情况。

For your example, you could write a simple unit test like this, using asserts :对于您的示例,您可以使用asserts编写一个像这样的简单单元测试:

def testSetTime():
    clock = Clock()
    clock.setTime(2, 18, 36)
    assert clock.getHours() == 2
    assert clock.getMinutes() == 18
    assert clock.getSeconds() == 36

Then you can add more tests as needed (note that each unit test should test only one thing).然后你可以根据需要添加更多的测试(注意每个单元测试应该只测试一件事)。

class Clock(object):
    def __init__(self, hour=12, minute=0, second=0, milTime=False):
        super(Clock,self).__init__()
        self.hour    = hour
        self.minute  = minute
        self.second  = second
        self.milTime = milTime  # 24-hour clock?

    @property
    def hour(self):
        return self._hour if self.milTime else ((self._hour-1) % 12)+1

    @hour.setter
    def hour(self, hour):
        self._hour = hour % 24

    @property
    def minute(self):
        return self._minute

    @minute.setter        
    def minute(self, minute):
        self._minute = minute % 60

    @property
    def second(self):
        return self._second

    @second.setter
    def second(self, second):
        self._second = second % 60

    @property
    def time(self):
        return self.hour, self.minute, self.second

    @time.setter
    def time(self, t):
        self.hour, self.minute, self.second = t

    def __str__(self):
        if self.milTime:
            return "{hr:02}:{min:02}:{sec:02}".format(hr=self.hour, min=self.minute, sec=self.second)
        else:
            ap = ("AM", "PM")[self._hour >= 12]
            return "{hr:>2}:{min:02}:{sec:02} {ap}".format(hr=self.hour, min=self.minute, sec=self.second, ap=ap)

then然后

c = Clock(12, 15, 10)
print c                 # -> 12:15:10 PM
c.milTime = True
print c                 # -> 12:15:10
c.hour = 9
print c                 # -> 09:15:10
c.milTime = False
print c                 # -> 9:15:10 AM
c.time = 12,34,2
print c                 # -> 12:34:02 PM

Getters and setters (c.getX() etc) are un-Pythonic; getter 和 setter(c.getX() 等)不是 Pythonic; if some translation is needed, use class property methods (as above), otherwise access the properties directly (as with Clock.milTime).如果需要一些转换,请使用类属性方法(如上),否则直接访问属性(如 Clock.milTime)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM