Think Python Exercise 17.0

我们做个练习, 将 time_to_int (见 16.4 节) 重写为方法。你或许也想将 int_to_time 改写为方法,但是那样做并没有什么意义,因为没有调用它的对象。

原 int_to_time 函数见练习16.0。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Time:
    """Represents the time of day."""
    def print_time(self):
        print("%.2d:%.2d:%.2d" % (self.hour, self.minute, self.second))
    def time_to_int(self):
        minutes = self.hour * 60 + self.minute
        seconds = minutes * 60 + self.second
        return seconds

start = Time()
start.hour = 9
start.minute = 45
start.second = 20

start.time_to_int()

我们做个练习,为 Point 类写一个 init 方法,使用 x 和 y 作为可选参数,然后赋值给对应的属性。

原相关代码见练习15.0。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Point:
    """表示一个二维的点
    """
    def __init__(self, x=0, y=0):
        self.x = x
        self.y = y
    def print_point(self):
        print('(%g, %g)' % (self.x, self.y))
        
Po1 = Point()
Po2 = Point(100,75)

Po1.print_point()
Po2.print_point()

我们做个练习,为 Point 类写一个 str 方法。然后创建一个 Point 对象并打印。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Point:
    """表示一个二维的点
    """
    def __init__(self, x=0, y=0):
        self.x = x
        self.y = y
    def __str__(self):
        return '(%g, %g)' % (self.x, self.y)
        
Po1 = Point()
Po2 = Point(100,75)

print(Po1)
print(Po2)

我们来做个练习,为 Point 类编写一个 add 方法。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Point:
    """表示一个二维的点
    """
    def __init__(self, x=0, y=0):
        self.x = x
        self.y = y
    def __str__(self):
        return '(%g, %g)' % (self.x, self.y)
    def __add__(self, other):
        return Point(self.x+other.x, self.y+other.y)
        
Po1 = Point(200,80)
Po2 = Point(100,75)

print(Po1+Po2)

我们做个练习,为 Points 编写一个 add 方法,使其既适用 Point 对象,也适用元组:

如果第二个运算数是一个 Point , 该方法将返回一个新的 Point, x 坐标是两个运算数的 x 的和,y 以此类推。

如果第二个运算数是一个元组,该方法将把元组的第一个元素与 x 相加,第二个元素与 y 相加,然后返回以相关结果为参数的新的 Point。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Point:
    """表示一个二维的点
    """
    def __init__(self, x=0, y=0):
        self.x = x
        self.y = y
    def __str__(self):
        return '(%g, %g)' % (self.x, self.y)
    def __add__(self, other):
        if isinstance(other, Point):
            return Point(self.x+other.x, self.y+other.y)
        else:
            return Point(self.x+other[0], self.y+other[1])
        
Po1 = Point(200,80)
Po2 = Point(100,75)

print(Po1+Po2)
print(Po1+(12,2))