龙空技术网

Python学习(十四)面向对象的三大特征(封装、继承、多态)

双鱼座的程序猿 282

前言:

现在姐妹们对“python变量前加self”可能比较看重,各位老铁们都需要剖析一些“python变量前加self”的相关资讯。那么小编在网络上搜集了一些关于“python变量前加self””的相关知识,希望各位老铁们能喜欢,姐妹们一起来了解一下吧!

面向对象-封装的实现方式

【面向对象的三大特征】  1、封装:【提高程序的(安全性)】    (1)将数据 (属性)和行为(方法)封装到类对象中。在方法内部对属性进行相关操作,     在内对象的外部调用封装的方法。不需要关心方法内部的具体实现细节,从而优化了程序的复杂度    (2)在Python中没有专门的修饰符用于修饰属性的私有化,如果类对象的属性不希望在外部被访问    ,前边可以使用两个"_"进行修饰。      2、继承:【提高程序代码的(复用性)】    3、多态:【提高程序代码的(可扩展性和可维护性)】

封装的代码实现

class Student:    def __init__(self,name,age):        self.name = name        self.__age = age # 年龄不希望在类对象的外部被使用,所以使用"__"进行修饰    def show(self):        print('学生的名字是:',self.name,',年龄是:',self.__age)stu = Student('张胜男','18')stu.show()# 在类对象的外部直接调用 "__" 修饰的属性 (AttributeError: 'Student' object has no attribute '__age')# print('学生的年龄是:',stu.__age)print('学生的年龄是:',stu._Student__age)# 使用dir()方法查看对象有哪些属性值print(dir(stu))
面向对象-继承的实现方式
【语法格式】  class 子类类名(父类1,父类2……):          pass(1)程序中,如果一个类没有继承任何类,则默认继承 object类(2)Python支持多继承(3)定义子类时,必须在其构造函数中调用父类的构造函数

继承的代码实现

# Person继承object类class Person(object):    def __init__(self,name,age):        self.name = name        self.age = age    def info(self):        print('姓名:{0},年龄:{1}'.format(self.name,self.age))        # print(self.name,self.age)# 定义子类class Student(Person):    def __init__(self,name,age,stu_no):        super().__init__(name,age)        self.stu_no = stu_no# 定义子类class Teacher(Person):    def __init__(self,name,age,teach_year):        super().__init__(name,age)        self.teach_year = teach_year# 定义属性对象stu = Student('Python',100,'1001')teacher = Teacher('Mr.Chang',27,3)# 调用方法stu.info()teacher.info()

方法重写含义及代码实现

(1)子类对继承父类的(某个方法)或(某个属性)有不同定义时,可以在子类中对其(方法体)重写(2)子类重写后的方法中可以通过 super(). 调用父类中被重写的方法
# Person继承object类class Person(object):    def __init__(self,name,age):        self.name = name        self.age = age    def info(self):        print('姓名:{0},年龄:{1}'.format(self.name,self.age))        # print(self.name,self.age)# 定义子类class Student(Person):    def __init__(self,name,age,stu_no):        super().__init__(name,age)        self.stu_no = stu_no    def info(self):        super().info()        print('学号:{0}'.format(self.stu_no))# 定义子类class Teacher(Person):    def __init__(self,name,age,teach_year):        super().__init__(name,age)        self.teach_year = teach_year    def info(self):        # super().info()        super(Teacher, self).info()        print('教龄:{0}'.format(self.teach_year),'年')# 定义属性对象stu = Student('Python',100,'1001')teacher = Teacher('Mr.Chang',27,3)# 调用方法stu.info()print('----------------------')teacher.info()

Object类

(1)object类是所有类的父类。所有类都有object类的属性和方法。(2)内置函数 dir() 可以查看指定对象的所有属性(3)Object有一个 '__str__()'方法,用于返回一个对于“对象的描述”,对应于内置函数 str() 经常用于print()方法。帮助我们查看对象的信息,所以我们经常会对 '__str()__'进行重写。
# Person继承object类  【__str__】class Person(object):    def __init__(self,name,age):        self.name = name        self.age = age    def __str__(self):        return '姓名:{0},年龄:{1}'.format(self.name,self.age)# 定义属性对象per = Person('阿瑟东',10)print(per)
面向对象-多态的实现方式
(1)简单的说,多态就是"具有多种形态"。它所指的是:即使我们不知道一个变量所引用的对象到底是什么类型,仍然可以通过这个变量调用方法。在运行过程中根据变量所引用对象的类型,动态决定调用哪个对象中的方法。
# Animal类继承object类class Animal(object):    def eat(self):        print('动物会吃')class Dog(Animal):    def eat(self):        print('狗吃骨头……')class Cat(Animal):    def eat(self):        print('猫吃鱼……')# Person类class Person:    def eat(self):        print('人吃五谷杂粮……')# 定义函数调用def fun(obj):    obj.eat()fun(Cat())fun(Dog())fun(Animal())print('-----------------------------')fun(Person())

静态语言与动态语言关于实现多态的区别

1、静态语言实现多态的三个必要条件:  (1)继承  (2)方法重写  (3)父类引用指向子类对象    2、动态语言的多态崇尚"鸭子类型":【当看到的一只鸟走起来像鸭子、游泳起来像鸭子、  收起来也像鸭子,那么这只鸟便可以称为"鸭子"。】即在动态语言中,不需要关心对象是什么类型, 只需要关心对象的行为即可。

特殊方法和特殊属性

【特殊属性 class Person(object):    def __init__(self,name,age):        print('默认初始化__init__()方法被调用了,self的id为:{0}'.format(id(self)))        self.name = name        self.age = age    def __new__(cls, *args, **kwargs):        print('__new__()被调用执行了,cls的id值为:{0}'.format(id(cls)))        obj = super().__new__(cls)        print('创建的对象的id为:{0}'.format(id(obj)))        return objprint('object这个类对象的id为:{0}'.format(id(object)))print('Person这个类对象的id为:{0}'.format(id(Person)))# 创建Person类的实例对象p = Person('张海峰',26)print('p这个Person类的实例对象的id为:{0}'.format(id(p)))__dict__() 】class A:    passclass B:    passclass C(A,B):    def __init__(self,name,age):        self.name = name        self.age = ageclass D(A):    pass# 创建C类的对象 [此处定义的x就是C类的一个实例对象]x = C('Python',100)# (实例对象)的属性字典:{'name': 'Python', 'age': 100}print('[__dict__]获得类对象或实例对象所绑定的所有属性和方法的字典',x.__dict__)# (类对象):{'__module__': '__main__', '__init__': <function C.__init__ at 0x000001E1C1B083A0>, '__doc__': None}print(C.__dict__)# 输出对象所属的类:<class '__main__.C'>print(x.__class__)# 输出父类的元组:(<class '__main__.A'>, <class '__main__.B'>)print(C.__bases__)# 输出继承的基类:<class '__main__.A'>print(C.__base__)# 输出类层次结构:(<class '__main__.C'>, <class '__main__.A'>, <class '__main__.B'>, <class 'object'>)print(C.__mro__)# 输出类的子类数组(列表):[<class '__main__.C'>, <class '__main__.D'>]print(A.__subclasses__())
print('===================特殊方法 __add__() =====================')a = 12b = 10# 两个整数类型的对象的相加操作c = a+bprint('整数类型的相加结果为:',c)d = a.__add__(b)print('[__add__]整数类型的相加结果为:',d)class Student:    def __init__(self,name):        self.name = name    # 定义特殊方法 __add__() 进行字符串相加    def __add__(self, other):        return self.name+other.name    # 定义特殊方法 __len__() 计算对象的长度    def __len__(self):        return len(self.name)stu1 = Student('张浩')stu2 = Student('徐冬梅')stu = stu1+stu2# 1、未添加__add__()特殊方法前报错: TypeError: unsupported operand type(s) for +: 'Student' and 'Student' 操作数据类型不支持# 2、在类中添加了__add__()特殊方法后,成功实现了两个对象的加法运算print('字符串相加结果(1)为:',stu)stu3 = stu1.__add__(stu2)print('字符串相加结果(2)为:',stu3)print('==============特殊方法 __len()__ =====================')lst = [12,33,45,67]print('列表的数据长度为:',lst.__len__())# 内置函数 len()print('列表的数据长度为:',len(lst))# 1、直接输出对象的长度报错:TypeError: object of type 'Student' has no len() 类型为“Student”的对象没有len()# 2、定义特殊方法后 __len__() 成功计算对象的长度print('对象的长度为:',len(stu2))
class Person(object):    def __init__(self,name,age):        print('默认初始化__init__()方法被调用了,self的id为:{0}'.format(id(self)))        self.name = name        self.age = age    def __new__(cls, *args, **kwargs):        print('__new__()被调用执行了,cls的id值为:{0}'.format(id(cls)))        obj = super().__new__(cls)        print('创建的对象的id为:{0}'.format(id(obj)))        return objprint('object这个类对象的id为:{0}'.format(id(object)))print('Person这个类对象的id为:{0}'.format(id(Person)))# 创建Person类的实例对象p = Person('张海峰',26)print('p这个Person类的实例对象的id为:{0}'.format(id(p)))

标签: #python变量前加self