美文网首页
继承中的特殊方法

继承中的特殊方法

作者: 泡菜鸡丁 | 来源:发表于2019-11-27 09:29 被阅读0次

    __init__方法

      __init__方法在类的一个对象被建立,马上运行。用来对你的对象初始化。

      注意,这个名称的开始和结尾都是双下划线。(__init__方法类似于c++,c#和Java中的constructor)

    class Peeson(self,name):

        def __init__(self,name):

              self.test_name = name

        def say(self):

              print("Hello,name is {}".format(self.name))

            self.test = "1234"

            # 属性可以随处定义,不需要先定义

            print("the test is "+self.test)

    P = Person("xiaoming")

    # 打印xiaoming,1234

    P.say()

    print("the Person test is "+p.test)

    p.test2 = "haha..."

    print("the Person test2 is "+p.test2)

    # 打印haha....

    名称      说明

    __init__(self) 这个方法在新建对象恰好要被返回使用之前被调用

    __del__(self) 在对象要被删除之前调用。如使用del删除

    __str__(self) 在我们对对象使用print语句或是使用str()的时候调用

    __lt__(self,other) 当使用小于 运算符(<)的时候调用

    __gt__(self,other) 当使用大于 运算符(>)的时候调用

    __eq__(self,other) 当使用等于 运算符(==)的时候调用

    __ne__(self,other) 当使用不等于 运算符(!=)的时候调用

    __le__(self,other) 当使用小于等于 运算符(<=)的时候调用

    __ge__(self,other) 当使用大于等于 运算符(>=)的时候调用

    __add__(self,other) 当使用加 运算符(+)的时候调用

    __getitem__(self,key) 当使用x[key] 索引操作符的时候调用

    __len__(self) 对序列对象使用内建的len()函数的时候调用

    相关文章

      网友评论

          本文标题:继承中的特殊方法

          本文链接:https://www.haomeiwen.com/subject/yuwuwctx.html