Python复习之__str__

from math import sqrt

class Point:
    def __init__(self, x=0, y=0):
        self.x = x
        self.y = y

    def move_to(self, x, y):
        """
            移动到新的坐标
        """
        self.x = x
        self.y = y

    def move_by(self, bx, by):
        """
            移动指定的增量
        """
        self.x += bx
        self.y += by

    def distance_to(self, other):
        dx = self.x - other.x
        dy = self.y - other.y
        return sqrt(dx ** 2 + dy ** 2)

    def __str__(self):
        """
        打印一个实例化对象时,打印的其实时一个对象的地址。
        而通过__str__()函数就可以帮助我们打印对象中具体的属性值,
        或者你想得到的东西
        """
        return ("%s, %s") % (str(self.x), str(self.y))
def main():
    p1 = Point()
    p2 = Point(3,4)
    print("p1: ", p1, "p2: ", p2)
    p2.move_to(4, 5)
    print(p2)
    p2.move_by(-1,-1)
    print(p2)
    distance = p2.distance_to(p1)
    print(distance)


if __name__ == '__main__':
    main()

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值