Python入门Day15:面向对象进阶(类变量,继承,封装,多态)
学习目标:
- 掌握类变量与实例变量的区别
- 学会类方法与静态方法的使用
- 理解继承的基本语法与方法重写
- 初步理解封装和多态的含义与应用
一、类变量 vs 实例变量
1.实例变量(每个对象独有)
class Person:def __init__(self,name):self.name = name #实例变量p1 = Person("Alice")
p2 = Person("Bob")
print(p1.name) #Alice
print(p2,name) #Bob
2.类变量(所有对象共享)
class Person:count = 0 # 类变量(统计总人数)def __init__(self.name):self.name = namePerson.count += 1print(Person.count) # 0
p1 = Person("A")
p2 = Person("B")
print(Person.count) # 2
二、类方法和静态方法
1.类方法(@classmethod)
- 第一个参数是cls,表示类本身
- 可用于操作类变量,创建工厂方法等
class Person:count = 0def __init__(self,name):self.name = namePerson.count += 1@classmethoddef get_count(cls):return cls.countprint(Person.get_count()) # 输出:0
p1 = Person("Tom")
print(Person.get_count()) # 输出:1
2.静态方法(@staticmethod)
- 不需要self或cls,想普通函数,但属于类组织的一部分
class MathTool:@staticmethoddef add(a,b):return a+bprint(MathTool.add(3,5)) # 输出:8
三、继承(Inheritance)
一个类可以继承另一个类的属性和方法,形成“父类-子类”结构。
class Animal:def speak(self):print("动物叫")class Dog(Animal):def bark(self):print("狗叫:汪汪")d = Dog()
d.speak() #继承自Animal
d.bark() #Dog自己的方法
四、封装(Encapsulation)
通过访问控制限制外部访问对象的内部实现。
私有属性与方法(用__开头)
class Account:def __init__(self,owner,balance):self.owner = ownerself.__balance = balance #私有属性def deposit(self,amount):if amount > 0:self.__balance += amountdef get_balance(self):return self.__balanceacc = Account("Tom",1000)
acc.deposit(500)
print(acc.get_balance()) #输出:1500
五、多态(Polymorphism)
不同类对象调用相同方法,呈现不同行为(统一接口,多种实现)
class Animal:def speak(self):passclass Dog(Animal):def speak(self):print("汪汪")class Cat(Animal):def speak(self):print("喵喵")def make_sound(animal):animal.speak()make_sound(Dog()) #汪汪
make_sound(Cat()) #喵喵