zoukankan      html  css  js  c++  java
  • Python class 重载方法

    Python面向对象的开发肯定离不开class,有点类似C语言的struct可以抽象描述对象并返回数据于方法。

    例如,建立一个class描述笛卡尔坐标系中的点:

    class point():
    
        def __init__(self, x, y):
            self.x = x
            self.y = y
            self.norm = (x * x + y * y) ** 0.5
    
        def __repr__(self):
            return '(%d,%d)'%(self.x,self.y)
    
        def __add__(self, other):
            x = self.x + other.x
            y = self.y + other.y
            return point(x,y)
    
        def __sub__(self, other):
            x = self.x - other.x
            y = self.y - other.y
            return point(x,y)
    
        def __del__(self):
            print(self,'has gone')
    
    a = point(2,3)
    b = point(1,1)
    print(a + b, a - b)
    
    #Output:
    #(3,4) (1,2)
    #(1,2) has gone
    #(3,4) has gone
    #(2,3) has gone
    #(1,1) has gone
    

    其中__init__为初始化方法,实例化时调用。
    __repr__为显示方法,被打印时调用
    __add____sub__分别重载加法和减法
    __del__为析构函数,对象被删除时调用
    本例中可以通过输出信息观察析构的顺序

  • 相关阅读:
    linux中nc命令
    Centos6.5 安装zabbix3(收藏,非原创)
    紀念
    算法学习资源收集
    一道奇怪的求和题
    P5717 题解
    P1424 刷题记录
    P1888 题解
    P1422 刷题记录
    P1055 题解
  • 原文地址:https://www.cnblogs.com/azureology/p/13039472.html
Copyright © 2011-2022 走看看