美文网首页
“魔法”方法

“魔法”方法

作者: 梦亦殇灬 | 来源:发表于2018-05-05 15:55 被阅读0次
    一、 init方法
    calss Dog():
      def __init__(self):
          self.color = "黄色"
          self.age  = 10
    taidi = Dog()
    

    init 方法会被默认调用

    二、str方法
    class Dog():
        def __init__(self,name):
            self.name = name
        def __str__(self):
            return   "小狗的名字是%s"%self.name
    dog  =Dog("哈士奇")
    print(dog)
    

    str 方法是打印对象是用的

    三、del方法
    class Car():
        def __del__(self):
            print("对象,你被干掉了")
    a = Car()
    b= Car()
    c =Car()
    del a
    del b 
    del c 
    

    只要删除一次对象,就调用一次del方法

    四、new方法
    class Dog():
        def __new__(cls):   #注意是cls
            print("这是new方法")
            return objiect.__new__(cls)
    dog = Dog()
    

    如果没有返回 那么就是重写Dog的父类new方法, 如果有就调用父类的new方法

    相关文章

      网友评论

          本文标题:“魔法”方法

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