大家好,欢迎来到 100 天精通 Python 基础篇第 12 天!
昨天我们初步认识了面向对象,今天深入学习类与对象的完整用法,把定义、实例化、属性、方法、封装一次性讲透。
一、回顾:类与对象是什么?
- 类(Class):对一类事物的抽象,是模板。
- 对象(Object):类的具体实例,是实实在在的个体。
举个例子:
二、定义类与创建对象
1. 定义类
2. 创建对象(实例化)
class Phone: passp = Phone()print(type(p)) # <class '__main__.Phone'>
三、构造方法 __init__
创建对象时自动调用,用于初始化属性。
class Phone: # 构造方法 def __init__(self, brand, price): self.brand = brand # 品牌 self.price = price # 价格# 创建对象时自动传参p1 = Phone("苹果", 5999)p2 = Phone("华为", 4999)print(p1.brand)print(p2.price)
四、self 到底是什么?
self 代表当前调用方法的对象自己class Phone: def __init__(self, brand): self.brand = brand def call(self): print(f"{self.brand} 手机正在打电话")p = Phone("小米")p.call() # self 就是 p
五、对象属性
1. 在 __init__ 中定义(推荐)
self.name = nameself.age = age
p = Phone("苹果", 5999)p.color = "白色" # 动态添加print(p.color)
六、类属性(所有对象共享)
类属性属于类本身,所有对象共用一份。
class Phone: # 类属性 type = "通讯工具" def __init__(self, brand): self.brand = brand# 访问类属性print(Phone.type)p1 = Phone("苹果")print(p1.type)
七、方法的分类
1. 对象方法(最常用)
第一个参数是 self,只能对象调用。
def call(self): print("打电话")
2. 类方法 @classmethod
第一个参数是 cls,可以类或对象调用。
@classmethoddef cls_func(cls): print("类方法", cls.type)
3. 静态方法 @staticmethod
无默认参数,相当于类里的普通函数。
@staticmethoddef static_func(): print("静态方法")
八、完整综合案例
class Student: # 类属性 school = "Python 学院" # 构造方法 def __init__(self, name, age): self.name = name self.age = age # 对象方法 def show_info(self): print(f"姓名:{self.name},年龄:{self.age}") # 类方法 @classmethod def show_school(cls): print(f"学校:{cls.school}") # 静态方法 @staticmethod def is_adult(age): return age >= 18# 创建对象s = Student("小明", 18)s.show_info()Student.show_school()print(Student.is_adult(18))
九、__dict__ 查看属性
查看对象拥有的所有属性:
print(s.__dict__)# {'name': '小明', 'age': 18}
十、面向对象小练习
定义一个 Car 类:
class Car: def __init__(self, brand, color, price): self.brand = brand self.color = color self.price = price def show(self): print(f"{self.color}{self.brand} 售价 {self.price}") def run(self): print(f"{self.brand} 在路上行驶")c = Car("奔驰", "黑色", 500000)c.show()c.run()
十一、今日重点总结
__init__ 构造方法初始化属性self 代表当前对象
掌握这些,你已经可以用面向对象写简单程序了。