Python 类中函数的特殊用法

Posted 神迹丶

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python 类中函数的特殊用法相关的知识,希望对你有一定的参考价值。

#类的重载
class Test:
    def __init__(self,n):
        self.num =n


    def __add__(self, other):    # 加法运算
        return Test(self.num+other.num)

    def __str__(self):  #当使用print输出类对象的时候,自动执行该函数,
        return \'Id 为:%s\'% self.num

    def __len__(self):  # 当对实例化类对象使用该函数时,返回该函数的长度
        return  len(str(self.num))

    def __del__(self):   #当程序被销毁时,自动执行该函数,相当于C++的析构函数
        print(\'%s,被释放\' % self.num)


t1=Test(\'1\')
t2=Test(2)

print(t1)
print(t2)

print(len(t1))
print(len(t2))

 

以上是关于Python 类中函数的特殊用法的主要内容,如果未能解决你的问题,请参考以下文章