我在CSDN学python-13

文章详细介绍了Python中面向对象编程的三大特征:封装、继承和多态。封装通过隐藏内部细节提高安全性,如使用`__init__`和`__str__`方法。继承允许代码复用,如`super()`调用父类方法。多态增强了程序的可扩展性,如不同类对象调用相同的`eat`方法。此外,文章还讨论了对象的`__dict__`、`__len__`、`__add__`等特殊属性和方法,以及浅拷贝和深拷贝的概念。
摘要由CSDN通过智能技术生成

面向对象的三大特征:

  • 封装:提高程序的安全性
  1. 将数据(属性)和行为(方法)包装到类对象中。在方法内部对属性进行操作,在类对象的外部调用方法。这样,无需关心方法内部的具体实现细节,从而隔离了复杂度。
  2. 在Python中没有专门的修饰符用于属性的私有,如果该属性不希望在类对象外部被访问,前边使用两个“_”。
  • 继承:提高代码的复用性
  • 多态:提高程序的可扩展性和可维护性

1、封装

# Name:      Python study
# Designer:  MilesHugh
# Time:      2023/4/12  15:38

class Car:
    def __init__(self, brand):
        self.brand = brand
    def start(self):
        print(self.brand + '汽车启动中ing...')

car = Car('宝马X5')
car.start()
print(car.brand)
# Name:      Python study
# Designer:  MilesHugh
# Time:      2023/4/13  11:09

class Student:
    def __init__(self, name, age):
        self.name = name
        self.__age = age  # 年龄不希望在类的外部被使用,所以加了两个_
    def show(self):
        print(self.name, self.__age)

stu = Student('张三', 20)
stu.show()
# 在类的外部使用name和age
print(stu.name)
# print(stu.__age) # age的内容不希望被使用
print(dir(stu))
print(stu._Student__age)  # 在类的外部可以通过_Student__age进行访问

2、继承

  • 语法格式
    class 子类类名(父类1, 父类2...):
        pass
  • 如果一个类没有继承任何类,则默认继承object
  • Python支持多继承
  • 定义子类时,必须在其构造函数中调用父类的构造函数
# Name:      Python study
# Designer:  MilesHugh
# Time:      2023/4/13  11:54

# 继承了方法和属性
class Person(object):  # Person继承object类
    def __init__(self, name, age):
        self.name = name
        self.age = age
    def info(self):
        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, teachofyear):
        super().__init__(name, age)
        self.teachofyear = teachofyear

stu = Student('张三', 20, '1001')
teacher = Teacher('李四', 34, 10)

stu.info()
teacher.info()


# 多继承
class A(object):
    pass

class B(object):
    pass

class C(A, B):
    pass

3、方法重写

  • 如果子类对继承自父类的某个属性或方法不满意,可以在子类中对其(方法体)进行重新编写
  • 子类重写后的方法中可以通过super().xxx()调用父类中被重写的方法
# Name:      Python study
# Designer:  MilesHugh
# Time:      2023/4/13  12:13

class Person(object):  # Person继承object类
    def __init__(self, name, age):
        self.name = name
        self.age = age
    def info(self):
        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('学号', self.stu_no)

class Teacher(Person):
    def __init__(self, name, age, teachofyear):
        super().__init__(name, age)
        self.teachofyear = teachofyear
    def info(self):   # 方法重写
        super().info()
        print('教龄', self.teachofyear)

stu = Student('张三', 20, '1001')
teacher = Teacher('李四', 34, 10)

stu.info()
print('--------')
teacher.info()

4、object类

  • object类是所有类的父亲,因此所有类都有object类的属性和方法。
  • 内置函数dir()可以查看指定对象所有属性
  • Object有一个_str_()方法,用于返回一个对于“对象的描述”,对应于内置函数str()经常用于print()方法,帮我们查看对象的信息,所以我们经常会对_str_()进行重写
# Name:      Python study
# Designer:  MilesHugh
# Time:      2023/4/13  12:24

class Student:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    def __str__(self):
        return '我的名字是{0},今年{1}岁。'.format(self.name, self.age)


stu = Student('张三', 20)
print(dir(stu))
print(stu)  # 默认调用__str__()这样的方法
print(type(stu))

5、多态

  • 多态就是“具有多种形态”,它指的是:即便不知道一个变量所引用的对象到底是什么类型,仍然可以通过这个变量调用方法,在运行中根据变量所引用对象的类型,动态决定调用哪个对象中的方法。
# Name:      Python study
# Designer:  MilesHugh
# Time:      2023/4/13  12:36

class Animal(object):
    def eat(self):
        print('动物会吃东西')
class Dog(Animal):
    def eat(self):
        print('狗吃骨头...')
class Cat(Animal):
    def eat(self):
        print('猫吃鱼肉...')

class Person:
    def eat(self):
        print('人吃五谷杂粮...')


# 定义一个函数
def fun(obj):
    obj.eat()

# 开始调用函数
fun(Cat())
fun(Dog())
fun(Animal())
print('---------')
fun(Person())  # 不存在继承关系,但Person()中有eat()方法,能调用

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

  • 静态语言实现多态的三个必要条件
  1. 继承
  2. 方法重写
  3. 父类引用指向子类对象
  • 动态语言的多态,为“鸭子类型”:不需要关心对象是什么类型,只关心对象的行为。可以在子类中补充父类没有的方法。
  • Python是动态语言,Java是静态语言

6、特殊方法和特殊属性

名称描述
特殊属性_dict_获得类对象或实例对象所绑定的所有属性和方法的字典
特殊方法_len_()通过重写_len_()方法,让内置函数len()的参数可以是自定义类型
_add_()通过重写_add_()方法,可以使用自定义对象具有“+”功能
_new_()用于创建对象
_init_()对创建的对象进行初始化

特殊属性:

_dict_的使用

# Name:      Python study
# Designer:  MilesHugh
# Time:      2023/4/13  16:11

print(dir(object))   # 查看object类的所有属性和方法

class A:
    pass
class B:
    pass
class C(A, B):
    def __init__(self, name, age):
        self.name = name
        self.age = age
class D(A):
    pass

# 创建C类的对象
x = C('miles', 22) # x是C类型的一个实例对象
print(x.__dict__)  # 实例对象的属性字典
print(C.__dict__)  # 类对象的属性、方法字典
print('------')
print(x.__class__)   # <class '__main__.C'> 输出对象所属的类
print(C.__bases__)   # C类的父类类型的元素
print(C.__base__)    # 输出C类的父类类型的第一个元素,类的基类
print(C.__mro__)   # 查看C类的层次结构
print(A.__subclasses__())   # 子类的列表

特殊方法:

_len_()和_add_()的使用

# Name:      Python study
# Designer:  MilesHugh
# Time:      2023/4/13  16:22

a = 20
b = 100
c = a + b  # 两个整数类型的对象相加操作
d = a.__add__(b)

print(c)
print(d)

class Student:
    def __init__(self, name):
        self.name = name
    def __add__(self, other):
        return self.name + other.name
    def __len__(self):
        return len(self.name)

stu1 = Student('张三')
stu2 = Student('李四')

s = stu1 + stu2  # 实现两个加法运算(因为在Student类中,编写__add__特殊的方法)
print(s)
s = stu1.__add__(stu2)
print(s)
print('------')
lst = [11, 22, 33, 44]
print(len(lst))   # len是内容函数len
print(lst.__len__())
print(len(stu1))

_new_()和_init_()的使用:

# Name:      Python study
# Designer:  MilesHugh
# Time:      2023/4/13  16:34

class Person(object):

    def __new__(cls, *args, **kwargs):   # 创建对象
        print('_new_被调用执行了,cls的id值为{0}'.format(id(cls)))
        obj = super().__new__(cls)
        print('创建的对象的id为:{0}'.format(id(obj)))
        return obj

    def __init__(self, name, age):   # 对对象的属性进行初始化使用
        print('__init__被调用了,self的id值为:{0}'.format(id(self)))
        self.name = name
        self.age = age
        
print('object这个类对象的id为:{0}'.format(id(object)))
print('Person这个类对象的id为:{0}'.format(id(Person)))

# 创建Person类的实例对象
p1 = Person('张三', 21)
print('p1这个Person类的实例对象的id为:{0}'.format(id(p1)))

7、类的浅拷贝与深拷贝

  • 变量的赋值操作:
  1. 只是形成两个变量,实际上还是指向同一个对象
  • 浅拷贝: 
  1.  Python拷贝一般都是浅拷贝,拷贝时,对象包含的子对象内容不拷贝,因此,源对象与拷贝对象会引用同一个子对象
  • 深拷贝: 
  1. 使用copy模块的deepcopy函数,递归拷贝对象中包含的子对象,源对象和拷贝对象所有的子对象也不相同。
# Name:      Python study
# Designer:  MilesHugh
# Time:      2023/4/13  16:51

class CPU:
    pass
class Disk:
    pass
class Computer:
    def __init__(self, cpu, disk):
        self.cpu = cpu
        self.disk = disk
# 1、变量的赋值
cpu1 = CPU()
cpu2 = cpu1
print(cpu1, id(cpu1))
print(cpu2, id(cpu2))

# 2、类有浅拷贝
print('---------')
disk = Disk()   # 创建一个硬盘类的对象
computer = Computer(cpu1, disk)  # 创建一个计算机类的对象

# 浅拷贝
import copy
print(disk)
computer2 = copy.copy(computer)   # 拷贝实例对象,所指向的子对象cpu、disk不拷贝
print(computer, computer.cpu, computer.disk)
print(computer2, computer2.cpu, computer2.disk)

# 深拷贝
print('-----------')
computer3 = copy.deepcopy(computer)   # 拷贝实例对象、以及所指向的子对象cpu、disk
print(computer, computer.cpu, computer.disk)
print(computer3, computer3.cpu, computer3.disk)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小翔很开心

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值