【Python】类与对象(进阶)
本文为 Python 学习笔记,讲解类与对象(进阶)。欢迎在评论区与我交流👏
封装
Python 中没有专门的关键字声明私有属性,若不希望该属性在类对象外部被访问,前面加 __:
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() print(stu.name) # print(stu.__age) # 报错
通过 print(dir(stu)) 查看所有属性:
可以看到 __age 被修改为了 _Student__age,因此可通过该属性名强行访问:
print(stu._Student__age)
继承
如果类没有继承任何类,默认继承 object
Python 支持多继承,即可以有多个父类
定义子类时,必须在构造函数中调用父类构造函数
demo:
class 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.teacherofyear=teachofyear stu=Student(张三, 20, 1001) teacher=Teacher(李四, 34, 10) stu.info() teacher.info()
多继承
demo:
class A(object): pass class B(object): pass class C(A, B): pass
方法重写
修改 Student 类,重写 info 方法。此时只能输出学号,无法输出 name 和 age:
class Student(Person): def __init__(self, name, age, stu_no): super().__init__(name, age) self.stu_no=stu_no def info(self): print(self.stu_no)
要输出姓名和年龄,就要调用父类中被重写的方法:
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)
object 类
所有类都有 object 类的属性和方法,dir 查看对象的所有属性:
class Student: pass stu=Student() print(dir(stu)) print(stu)
输出结果:
直接输出对象的内存地址。
__str__() 方法返回对象描述:
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__() 方法
多态
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())
输出结果:
动态语言的多态不关心对象类型,只关心对象的行为。
特殊方法和特殊属性
持续更新。。。