美文网首页
Python面向对象

Python面向对象

作者: 嘤嘤嘤998 | 来源:发表于2019-05-07 17:30 被阅读0次
    image.png
    • 对象: image.png image.png image.png image.png
    • 类和对象的创建 image.png
    class Cat:
        def eat(self):
            print("猫吃鱼")
        def drink(self):
            print("猫喝水")
    tom = Cat()
    tom.eat()
    tom.drink()
    
    • 引用 image.png image.png image.png image.png
    • self参数: image.png
      init方法(创建对象时,自动调用) image.png image.png
      使用参数设置属性初始值 image.png image.png image.png image.png
    class Cat:
        def __init__(self, name):
            self.name = name
            print("%s 来了" % self.name)
        def __del__(self):
            print("%s 走了" % self)
    
    tom = Cat("Tom")
    print (tom.name)
    print("-" * 50)
    #输出结果:
    Tom来了  #init初始化后马上调用
    Tom
    -------------------------------------   
    Tom走了  #del销毁前调用。 tom是全局变量,会在所有代码执行完之后才会销毁
    
    class Person:
        def __init__(self, name, weight):
            self.name = name
            self.weight = weight
        def __str__(self):
            return "我的名字叫 %s 我的体重是 %.2f" % (self.name, self.weight)
        def run(self):
            self.weight -= 1
        def eat(self):
            self.weight += 1
            
    tom = Person("Tom", 75.0)
    tom.run()
    tom.eat()
    print(tom)
    
    image.png
    • 可以使用 image.png
    • 身份运算符 image.png
    • 私有属性和私有方法 image.png

    继承

    image.png
    子类拥有父类的所有方法和属性 image.png image.png
    • 重写 image.png
    • 扩展父类方法,super对象调用父类方法 image.png
    • 父类的私有属性方法 image.png
    • 多继承 image.png
    • 新式类和经典类 image.png
    • 实例 image.png
    • 类属性 image.png image.png
    • 类方法 image.png
    • 静态方法 image.png image.png
    • new方法 image.png
    • 单例方法 image.png image.png
    • 初始化动作只执行一次 image.png

    相关文章

      网友评论

          本文标题:Python面向对象

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