十九、面向对象编程

十九、面向对象编程

类与对象

类是总结事物特征的抽象概念,是创建对象的模板。对象是按照类来具体化的实物。

类的构成

类的名称:类名
类的属性:一组参数数据
类的方法:操作的方式或行为

类的创建

# class People(object): 新式类 class People(): 经典类
class People(object): # 类名,python建议使用大驼峰命名(每一个单词的首字母都采用大写字母);
    def __init__(self, name, sex): # 类的属性
        self.name = name
        self.sex = sex

    def info(self): # 类的方法
        print(self.name, self.sex)

p1 = People("张三", "男")
p2 = People("李四", "女")
p1.info()

举例说明

class Hero(object):

    money = 300  # 类变量

    def __init__(self, name, job, HP, MP, attack, defence):
        self.name = name
        self.job = job
        self.HP = HP
        self.MP = MP
        self.attack = attack
        self.defence = defence

    def info(self):
        print("""
        英雄:{}
        职业:{}
        血量:{}
        蓝量:{}
        攻击:{}
        防御:{}
        金币:{}
        """.format(self.name, self.job, self.HP, self.MP, self.attack, self.defence, self.money))

h1 = Hero("亚瑟", "战士", 1000, 100, 100, 80)
h2 = Hero("后羿", "射手", 800, 100, 120, 50)
h1.info()
h2.money = 500
h2.info()

_str__与__del__(了解)

class Hero(object):
    def __init__(self,name):
        self.name=name
    def __str__(self): # print(对象)会输出__str__函数的返回值
        return "我叫{},我为自己代言".format(self.name)
    def __del__(self): # 对象调用完销毁时,会调用此函数
        print("......我{}还会回来的......".format(self.name))
hero1=Hero("亚瑟")
hero2=Hero("后羿")

print(hero1)
print(hero2)

del hero1
del hero2  # 把这两句del注释分别打开,会有不同的效果
print("="*30)

小结

方法 描述
def _init_(self) 创建对象的时候自动调用此方法
def _str_(self) print(对象)时调用此方法
def _del_(self) 对象被销毁的时候自动调用该方法,做一些收尾工作,如关闭打开的文件,释放变量等

私有属性与私有方法(拓展)

一般情况下,私有的属性、方法都是不对外公布的,往往用来做内部的事情,起到安全的作用。
python没有像其它语言那样有public,private等关键词来修饰,而是在变量前加__来实现私有。
举例说明:

class People(object):
    __country="china" # 前面加上__,那么就做成了私有属性,就不能被类的外部直接调用
    def __init__(self,name,sex):
        self.name=name
        self.__sex=sex # 前面加上__,那么就做成了私有属性,就不能被类的外部直接调用
    def __info(self): # 前面加上__,那么就做成了私有方法,就不能被类的外部直接调用
        print(self.name,self.sex)
p1=People("zhangsan","man")
# print(p1.sex)
# print(p1.__sex)
# print(p1.country)
# print(p1.__country)
# p1.info()
# p1.__info() # 这六句单独打开注释验证,都会报错。不能调用私有属性和私有方法

如果类的外部需要调用到私有属性的值,可以对私有属性单独定义一个类的方法,让实例通过调用此方法来调用私有属性(私有方法同理)

class People(object):
    __country="china"  # 私有类变量
    def __init__(self,name,sex):
        self.name=name
        self.__sex=sex  # 私有属性
    def __info(self):  # 私有方法
        print(self.name,self.__sex)
    def show_sex(self): # 定义一个方法来调用私有方法
        print(self.__sex)
    def show_country(self):
        print(self.__country)
    def show_info(self):
        People.__info(self)
p1=People("zhangsan","man")
p1.show_sex()
p1.show_country()
p1.show_info()

小结:
内部属性不希望被外部调用与修改就可以做成私有的。

面向对象三大特性:

1. 封装
2. 继承
3. 多态

继承

继承的作用: 减少代码的冗余,便于功能的升级(原有的功能进行完善)与扩展(原没有的功能进行添加)
举例说明

class People(object):
    def __init__(self, name, age):
        self.name = name
        self.age = age
    def eat(self):
        print("{}正在吃".format(self.name))
    def drink(self):
        print("{}正在喝".format(self.name))

class Man(People):
    def work(self):
        print("{}正在工作".format(self.name))
        self.eat()
        self.drink()
    def eat(self):  # 在子类里写了一个和父类相同的方法,那么对这个子类实例化,调用此方法,子类方法会优先生效(方法重写)
        print("{}正在狼吞虎咽".format(self.name))


class Woman(People):
    def __init__(self, name, age, love_shopping):
        self.name = name
        self.age = age
        self.love_shopping = love_shopping
    # 或
    # def __init__(self, name, age, love_shopping):
    #     super(Woman, self).__init__(name, age)
    #     self.love_shopping = love_shopping

    def info(self):
        if self.age > 18 and self.love_shopping == True:
            print("{}出去买吧".format(self.name))

m1 = Man("张三", 30)
m2 = Man("王五", 28)
w1 = Woman("李四", 25, True)

m1.work()
m2.work()
w1.info()

多层继承(了解)多层继承(了解)

示例: 多层继承例一

class Grandfather():
    def house(self): # 爷爷类的方法
        print("a big house!")
class Father(Grandfather): # 爸爸类继承爷爷类
    def car(self):
        print("a cool car!")
class child(Father): # 孩子类继承爸爸类
    pass
p1=child() # 实例化一个孩子
p1.house() # 这个孩子对象可以调用爷爷的方法

示例: 多层继承例二

class People():
    def __init__(self, name, sex):
        self.name = name
        self.sex = sex
class Love(People):
    def fall_in_love(self,obj):
        if self.sex == "男":
            print("{}向{}求婚".format(self.name,obj.name))
        elif self.sex == "女":
            print("{}要给{}生猴子".format(self.name,obj.name))
        else:
            print("性别输入有误")
class Man(Love):
    pass
class Woman(Love):
    pass
m1=Man("张三","男")
w1=Woman("李四","女")
m1.fall_in_love(w1)
w1.fall_in_love(m1)

多继承(了解)

支持面向对象编程的开发语言中,支持多继承的语言并不多,像java,php这些都只支持单继承。支持多继承的主要就是python,c++。

什么是多继承?
答: 多继承,即子类有多个父类,并且具有它们的特征。

示例: 多继承例一

class Father(object):
    def sing(self):
        print("can sing")
class Mother(object):
    def dance(self):
        print("can dance")
class child(Father,Mother): # 继承Father,Mother两个父类
    pass
p1=child()
p1.sing() # 可以用Father的方法
p1.dance() # 也可以用Mother的方法

示例: 多继承例二

class People():
    def __init__(self, name, sex):
        self.name = name
        self.sex = sex
class Love():
    def fall_in_love(self,obj):
        if self.sex == "男": # 这里的sex变量在Love类里并没有定义
            print("{}向{}求婚".format(self.name,obj.name))
        elif self.sex == "女":
            print("{}要给{}生猴子".format(self.name,obj.name))
        else:
            print("性别输入有误")
class Man(People,Love): # Love里没有sex变量,People里有sex变量,多继承合到一起就OK
    pass
class Woman(People,Love):
    pass
m1=Man("张三","男")
w1=Woman("李四","女")
m1.fall_in_love(w1)
w1.fall_in_love(m1)
posted @ 2023-06-28 17:59  村尚chun叔  阅读(8)  评论(0编辑  收藏  举报