zoukankan      html  css  js  c++  java
  • 11.面对对象编程

    十一、面对对象编程

    类定义:

    类名:
    属性:
    功能:
    class Cat():#类名为Cat
        #属性
    
    
        #方法
        def eat(self):
            print("mao zai chi yu")
            
        def drink(self):
            print("mao is a doog")
            
        def introduce(self):
            print("%s的年龄是:%d"%(self.name, self.age))#self变量指向自己
                                                        #self谁调用就指向谁,self为第一个参数
    tom = Cat()
    tom.eat()
    tom.drink()
    tom.name = "汤姆"#添加属性
    tom.age = 40
    tom.introduce()#相当于  tom.introduce(tom)
    
    lan = Cat()
    lan.eat()
    lan.drink()
    lan.name = "蓝猫"
    lan.age = 100
    lan.introduce()

    有__init__方法时:  __init__(self)   

    class Cat():#类名为Cat
        """定义一个Cat类"""
        
        #属性
        
        #初始化对象
        def __init__(self):
            print("******")#python自动调用__init__(self)方法
    
        #方法
        def eat(self):
            print("mao zai chi yu")
            
        def drink(self):
            print("mao is a doog")
            
        def introduce(self):
            print("%s的年龄是:%d"%(self.name, self.age))#self变量指向自己
                                                        #self谁调用就指向谁,self为第一个参数
    
    #创建一个对象
    tom = Cat()
    tom.eat()
    tom.drink()
    tom.name = "汤姆"#添加属性
    tom.age = 40
    tom.introduce()#相当于  tom.introduce(tom)
    
    lan = Cat()
    lan.eat()
    lan.drink()
    lan.name = "蓝猫"
    lan.age = 100
    lan.introduce()
    """
    创建对象的过程:
    1、创建一个对象
    2、python自动调用__init__方法
    3、返回创建的对象的引用 给tom
    
    """

    有__init__方法时:  __init__(self, x, y[,z])     #多参数

    class Cat():#类名为Cat
        """定义一个Cat类"""
        
        #属性
        
        #初始化对象
        def __init__(self, new_name, new_age):#python自动调用__init__(self)方法
            self.name = new_name
            self.age = new_age
            
        #方法
        def eat(self):
            print("mao zai chi yu")
            
        def drink(self):
            print("mao is a doog")
            
        def introduce(self):
            print("%s的年龄是:%d"%(self.name, self.age))#self变量指向自己
                                                        #self谁调用就指向谁,self为第一个参数
    
    #创建一个对象
    tom = Cat("汤姆",40)
    tom.eat()
    tom.drink()
    tom.introduce()#相当于  tom.introduce(tom)
    
    lan = Cat("蓝猫",100)
    lan.eat()
    lan.drink()
    lan.introduce()
    """
    创建对象的过程:
    1、创建一个对象
    2、python自动调用__init__方法
    3、返回创建的对象的引用 给tom
    
    """

    __str__(self)方法:自动调用对象的属性

    class Cat():#类名为Cat
        """定义一个Cat类"""
        
        #属性
        
        #初始化对象
        def __init__(self, new_name, new_age):#python自动调用__init__(self)方法
            self.name = new_name
            self.age = new_age
            
        def __str__(self):
            return "%s的年龄是%d"%(self.name, self.age)
            
        #方法
        def eat(self):
            print("mao zai chi yu")
            
        def drink(self):
            print("mao is a doog")
            
        def introduce(self):
            print("%s的年龄是:%d"%(self.name, self.age))#self变量指向自己
                                                        #self谁调用就指向谁,self为第一个参数
    
    #创建一个对象
    tom = Cat("汤姆",40)
    
    lan = Cat("蓝猫",100)
    
    print(tom)
    print(lan)

     属性多次变化

    class SweetPotato:
    
        def __init__(self):
            self.cookedString = "生的"
            self.cookedLevel = 0
            self.condiments = []
    
        def __str__(self):
            return "地瓜 状态:%s(%d),添加的作料有:%s"%(self.cookedString, self.cookedLevel, str(self.condiments))
    
        def cook(self, cooked_time):
    
            self.cookedLevel += cooked_time
            
            if self.cookedLevel >= 0 and self.cookedLevel < 3:
                self.cookedString = "生的"
            elif self.cookedLevel >= 5 and self.cookedLevel <8:
                self.cookedString = "熟了"
            elif self.cookedLevel >8:
                self.cookedString = "烤糊了"
    
        def addCondiments(self, item):
            self.condiments.append(item)
            
            
    #创建了一个地瓜对象
    di_gua = SweetPotato()
    
    #开始烤地瓜
    di_gua.cook(1)
    print(di_gua)
    di_gua.cook(1)
    print(di_gua)
    di_gua.cook(1)
    print(di_gua)
    di_gua.cook(1)
    print(di_gua)
    di_gua.addCondiments("大蒜")
    print(di_gua)
    di_gua.cook(1)
    print(di_gua)
    di_gua.cook(1)
    print(di_gua)
    di_gua.addCondiments("辣椒")
    print(di_gua)
    di_gua.cook(1)
    print(di_gua)
    di_gua.cook(1)
    print(di_gua)
    di_gua.addCondiments("芥末")
    print(di_gua)
    di_gua.cook(1)
    print(di_gua)
    di_gua.cook(1)
    print(di_gua)

    把一个对象添加到另外一个属性中

    class Home:
    
        def __init__(self, new_area, new_info, new_addr):
            self.area = new_area
            self.info = new_info
            self.addr = new_addr
            self.left_area = new_area
            self.contain_items = []
    
        def __str__(self):
    
            msg = "房子的总面积是:%d,可用面积:%d,户型是:%s,地址是:%s"%(self.area, self.left_area, self.info, self.addr)
            msg += "当前房子里面的物品有:%s"%(str(self.contain_items))
            return msg
    
    
        def add_item(self, item):
            self.left_area -= item.area
            self.contain_items.append(item.name)
    
    
    class Bed:
        def __init__(self, new_name, new_area):
            self.name = new_name
            self.area = new_area
    
        def __str__(self):
            return "%s 占用的面积是:%d"%(self.name, self.area)
    fangzi = Home(129, "三室一厅","北京市 朝阳区 长安街 666号")
    print(fangzi)
    
    bed1 = Bed("席梦思",4)
    print(bed1)
    
    fangzi.add_item(bed1)
    print(fangzi)
    
    bed2 = Bed("三人床",3)
    fangzi.add_item(bed2)
    print(fangzi)
                      
    一、
    设计类
    类名:见名知意,首字母大写,其他遵循驼峰原则
    属性:见名知意,其他遵循驼峰原则
    行为(方法/功能):见名知意,其他遵循驼峰原则
    
    创建类
    类:一种数据类型,本身并不占内存空间,和前面所学,number, stringm boolean
    等类似。用类创建实例化对象,对象占内存空间
    
    格式:
    class 类名(父类列表):
      属性
      行为
    
    # object:基类, 超类, 所有类的父类
    # 一般没有合适的父类就写object
    
    
    class Person(object):
    
    
      #定义属性(定义变量)
      name = ""
      age = 0
      height = 0
      weight = 0
    
      #定义方法(定义函数)
      #注意:方法的参数必须以self当第一个参数
      def run(self):#类中的第一个参数一定是self
        print("run")
      def eat(self, food):
        print("eat"+food)
    
    
    二、
    class Person(object):
        #定义属性(定义变量)
        name = ""
        age = 0
        height = 0
        weight = 0
    
        #定义方法(定义函数)
        #注意:方法的参数必须以self当第一个参数
        def run(self):#类中的第一个参数一定是self
            print("run")
        def eat(self, food):
            print("eat"+food)
        def openDoor(self):
            print("我已经打开并行们")
        def fillEle(self):
            print("我已经把大象装进冰箱")
        def closeDoor(self):
            print("我已经关闭了冰箱门")
    """
    实例化对象
    格式: 对象名 = 类名(参数列表)
    注意:没有参数,小括号也不能省略
    
    """
    #实例化一个对象
    per1 = Person()
    print(per1)
    
    per2 = Person()
    print(per2)
     
     

    """
    写重复代码时非常低级的行为
    你写的代码需要经常的变更

    """

     11-1  定义类,创建对象,,添加属性,调用方法

    class Car:
        def run(self):
            print("车在跑")
        def toot(self):
            print("嘟嘟嘟嘟的。。。。。")
    
    car = Car()
    car.color = "黑色"
    
    print(car.color)
    
    car.run()
    car.toot()

    11-2  构造方法__init__对类自动初始化

    class Car:
        # 构造方法
        def __init__(self):  # 无论创建多少个对象都是默认黑色
            self.color = "黑色"
        # 鸣笛
        def toot(self):
            print("%s的车在鸣笛。。。"%(self.color))
    # 创建对象
    car = Car()
    # 汽车鸣笛
    car.toot()
    class Car:
        # 构造方法
        def __init__(self, color):  # 带参数的初始化
            self.color = color
        # 鸣笛
        def toot(self):
            print("%s的车在鸣笛。。。。"%(self.color))
    
    car1 = Car('heise')
    car1.toot()
    
    car2 = Car('黑色')
    car2.toot()

    11-4  析构方法:释放类占用的资源

    class Car:
        def __init__(self, age, name):
            self.age = age
            self.name = name
        def __del__(self):  # 析构方法
            print("="*20)
    
    car = Car(30, "xiaohe")

    11-5  self 方法的使用

    # self 方法的使用
    
    class Dog:
        def __init__(self, new_color):
            self.new_color = new_color
        def print_color(self):
            print("颜色为:%s"%(self.new_color))
    
    dog_white = Dog('white')
    dog_white.print_color()
    
    dog_black = Dog("黑色")
    dog_black.print_color()

    11-12

    12.1  封装(隐藏数据、保护属性)

    class Person:
        def __init__(self, name, age):
            self.name = name
            self.age = age
    
    person = Person("wang", 23)
    person.age = 300
    print(person.age)

     例12-1私有属性

    # 私有属性
    class Person:
        def __init__(self, name, age):
            self.name = name
            self.age = age
        # 给私有属性赋值
        def set_age(self, new_age):
            # 判断传入的参数是否符合要求,符合后才能赋值
            if new_age > 0 and new_age <= 120:
                self.__age = new_age    # 私有属性:属性名前加两个下划线
        # 获取私有属性的值
        def get_age(self):
            return self.__age
    # 创建对象
    person.set_age(30)
    print(person.get_age())

    12.2  继承:描述事物之间的从属关系

      单继承

    class 子类(父类)
    # 单继承
    class Cat(object):
        def __init__(self, color = "白色"):
            self.color = color      # 颜色
        def run(self):
            print("=====跑======")
    
    class PersianCat(Cat):  # 继承使用
        pass
    
    cat = PersianCat("黑色")
    cat.run()
    print(cat.color)

      多继承(一个子类有多个父类)

    class 子类(父类1, 父类2......)
    # 多继承
    class Bird(object):
        #
        def fly(self):
            print("==鸟儿在天空飞翔==")
    # 定义表示鱼的类
    class Fish(object):
        #
        def swim(self):
            print("==鱼儿在水中遨游==")
    # 定义表示飞鱼的类
    class Volador(Bird, Fish):
        pass
    volador = Volador()
    volador.fly()
    volador.swim()

      重写父类 (覆盖父类方法)

    # 重写父类
    class Person(object):
        # 打招呼的方式
        def say_hello(self):
            print("===hello===")
    # 定义Chiese类继承自Person类
    class Chinese(Person):
        # 中国人打招呼的方式
        def say_hello(self):
            print("吃了吗?")
    # 创建Chiese类的对象
    chinese = Chinese()
    chinese.say_hello()

    # 子类与父类的方法名相同,调用子类时直接覆盖父类的方法

      调用父类(在父类方法、属性的基础上新增加子类的方法、属性)

    """父类方法调用"""
    
    # 定义父类Animal
    class Animal(object):
        def __init__(self, leg_count):
            # 腿的数量
            self.leg_count = leg_count
    
    # 定义Bird类的继承自Animal
    class Bird(Animal):
        # 重写父类的init方法
        def __init__(self, leg_count):
            # 增加特有属性
            self.plume = "白色"
            # 调用父类的init方法
            super().__init__(leg_count)
    bird = Bird(2)
    print("%s条腿%s羽毛"%(bird.leg_count, bird.plume))

    12.3  多态

        不考虑对象类型的情况下使用对象

    class Animal(object):
        # 定义一个父类
        def test(self):
            print("===Animal===")
    class Bird(Animal):
        def test(self):
            print("===Bird===")
    
    def func(temp):
        temp.test()
    
    animal = Animal()
    bird = Bird()
    func(animal)
    func(bird)

    12-7  多态

    # 多态
    
    class Animal(object):
        def shout(self):
            print("===Animal----shout====")
    
    class Dog(Animal):
        def shout(self):
            print("---wang---")
    
    class Cat(Animal):
        def shout(self):
            print("===miao===")
    
    def func(temp):
        temp.shout()
    
    dog = Dog()
    func(dog)
    
    cat = Cat()
    func(cat)

    12.4  类属性、实例属性

    # 类属性和实例属性
    
    class Cat(object):
        # 类属性
        number = 0
        def __init__(self):
            # 实例属性
            self.age = 1
    
    cat = Cat()
    print(cat.number)
    # 通过实例访问实例属性
    print(Cat.number)
    # 通过类去访问类属性

    12.5  类方法、静态方法

      类方法

    # 类方法
    class Test(object):
        # 类属性
        number = 0
        # 类方法
        @classmethod
        def set_number(cls, new_number):
            cls.number = new_number
    
    Test.set_number(3003)
    print(Test.number)

      静态方法

    class Test(object):
        @staticmethod
        def print_test():
            # 静态方法没有参数
            print("我是静态方法")
    
    Test.print_test()
    test =  Test()
    test.print_test()

    案例:

    # 定义表示战士、敌人的类
    class Person:
        def __init__(self, name):
            # name
            self.name = name
            # 血量
            self.blood = 100
    
        # 给弹夹安装子弹
        def install_bullet(self, clip, bullet):
            # 弹夹放置子弹
            clip.save_bullets(bullet)
    
    # 定义表示弹夹的类
    class Clip:
        def __init__(self, capacity):
            # 最大容量
            self.capacity = capacity
            # 当前子弹数量
            self.current_list = []
        # 安装子弹
        def save_bullets(self, bullet):
            # 当前子弹数量小于最大容量
            if len(self.current_list) < self.capacity:
                self.current_list.append(bullet)
    
        # 出子弹
        def launch_bullet(self):
            # 判断当前弹夹中是否还有子弹
            if len(self.current_list) > 0:
                bullet = self.current_list[-1]
                self.current_list.pop()
                return bullet
            else:
                return None
            
    
    # 定义表示子弹的类
    class Bullet:
        pass
    
    # 创建一个战士
    soldier = Person("老王")
    # 创建一个弹夹
    clip = Clip(20)
    print(clip)
    # 添加5枚子弹
    i= 0
    while i < 5:
        # 创建一个子弹
        bullet = Bullet()
        # 战士安装子弹到弹夹
        soldier.install_bullet(clip, bullet)
        i += 1
    # 输出当前弹夹中子弹的数量
    print(clip)
    
    def __str__(self):
        return "弹夹当前的子弹数量为:"+str(len(self.current_list))+"/"+str(self.capacity)
    
    # 给抢安装弹夹
    def install_clip(self, gun, clip):
        # 枪链接弹夹
        gun.mounting_clip(clip)
    
    # 定义表示枪的类
    class Gun:
        def __init__(self):
            # 默认没有弹夹
            self.clip = None
        def __str__(self):
            if self.clip:
                return "枪当前有弹夹"
            else:
                return "枪没有弹夹"
        # 链接弹夹
        def mounting_clip(self, clip):
            if not self.clip:
                self.clip = clip
        # 射击
        def shoot(self, enemy):
            
    
    
    
        
    # 创建一个枪
    gun = Gun()
    print(gun)
    # 安装弹夹
    soldier.install_bullet(gun, clip)
    print(gun)
    
    # 持枪
    def take_gun(self, gun):
        self.gun = gun
    # 开枪
    def fire(self, enemy):
        # 射击敌人
        self.gun.shoot(enemy)
    # 射击
    def shoot(self, enemy):
        # 弹夹出子弹
        self.clip.launch_bullet()
        
  • 相关阅读:
    yii2 gii 命令行自动生成控制器和模型
    控制器中的方法命名规范
    Vue Property or method "" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based
    IDEA插件:GsonFormat
    Spring Boot : Access denied for user ''@'localhost' (using password: NO)
    Typora添加主题
    Git基础命令图解
    Java Joda-Time 处理时间工具类(JDK1.7以上)
    Java日期工具类(基于JDK1.7版本)
    Oracle SQL Developer 连接Oracle出现【 状态: 失败 -测试失败: ORA-01017: invalid username/password; logon denied】
  • 原文地址:https://www.cnblogs.com/xieyi-newlife/p/8969524.html
Copyright © 2011-2022 走看看