深入理解 Python 面向对象编程
·
深入理解 Python 面向对象编程
—— 类与对象的基本概念、属性和方法分类及使用场景
在 Python 中,一切皆对象。面向对象编程(Object-Oriented Programming,简称 OOP)是 Python 的核心编程范式之一,它使我们可以通过“类”和“对象”来模拟现实世界的各种事物与行为。
一、什么是类和对象?
-
类(Class):是对一类事物的抽象,比如“人类”、“汽车”、“字符串”等。
-
对象(Object):是类的具体实例,比如“张三”、“特斯拉Model S”、“Hello”。
类是模板,对象是具体产品
人类(类) / \ 张三 李四 (对象) 汽车(类) / \ 特斯拉 宝马 (对象)
示例:定义一个类和创建对象
class Human:
def __init__(self, username, birthday, gender):
self.username = username
self.birthday1 = birthday
self.gender = gender
def showme(self):
return f"我是{self.username},出生于{self.birthday1},性别{self.gender}"
p1 = Human("小张", "2000-01-01", "男")
print(p1.showme())
我是小张,出生于2000-01-01,性别男
二、属性的分类
1. 实例属性
每个对象独有的数据:
class Dog: def __init__(self, name, color): self.name = name self.color = color
dog1 = Dog("京巴", "黄色")
dog2 = Dog("泰迪", "棕色")
2. 类属性
所有对象共享的数据,通常用于存放常量或全局设置:
class BankCard:
interest = {3: 0.008, 6: 0.010, 12: 0.015} # 类属性
def __init__(self, cardid, name, money=0):
self.cardid = cardid
self.name = name
self.money = money
print(BankCard.interest)
三、方法的分类
1. 实例方法(普通方法)
操作当前对象的数据,必须接收 self 参数:
class Dog:
def __init__(self, name, color):
self.name = name
self.color = color
def speak(self):
return f"我叫{self.name},是一只{self.color}的小狗"
d = Dog("京巴", "橘黄色")
print(d.speak())
2. 类方法(@classmethod)
操作类本身,使用 cls 参数。通常用于创建对象的“快捷工厂”方式:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
@classmethod
def create(cls, info):
name, age = info.split(',')
return cls(name, int(age))
p2 = Person.create("xxx,20")
print(p2.name, p2.age)
工厂模式应用:
class AnimalFactory: @classmethod def create(cls, info): if info['type'] == 'Dog': return Dog(**info) elif info['type'] == 'Cat': return Cat(**info)
3. 静态方法(@staticmethod)
既不访问实例,也不访问类,只是与类逻辑相关的工具函数:
class MyMath: @staticmethod def add(a, b): return a + b print(MyMath.add(100, 200))
四、魔术方法(Magic Methods)
Python 中使用 __xxx__ 命名的特殊方法可以重载内建操作符行为。
1. __init__() 与 __new__()
class MyClass:
def __new__(cls, *args, **kwargs):
print("调用 __new__ 方法,创建对象")
return super().__new__(cls)
def __init__(self, value):
print("调用 __init__ 方法,初始化对象")
self.value = value
2. __str__():对象的友好表示
class list:
def __init__(self, value):
self.value = value
def __str__(self):
return f'[{", ".join(map(str, self.value))}]'
l1 = list([1, 2, 3])
print(l1)
3. __len__():支持 len() 函数
class list: def __init__(self, value): self.value = value def __len__(self): return len(self.value) l1 = list([1, 2, 3]) print(len(l1)) # 输出 3
五、自定义类模拟内建类
模拟 str 类部分行为
class str:
def __init__(self, value):
self.value = value
def capitalize(self):
return self.value[0].upper() + self.value[1:].lower()
s = str("hello WORLD")
print(s.capitalize()) # Hello world
六、方法类型对比总结
| 方法类型 | 是否访问实例属性 | 是否访问类属性 | 使用场景 |
|---|---|---|---|
| 实例方法 | ✅ | ❌ | 操作具体对象 |
| 类方法 | ❌ | ✅ | 操作类级数据、工厂模式 |
| 静态方法 | ❌ | ❌ | 工具方法、逻辑归类 |
| 魔术方法 | ✅ / ❌ | ✅ / ❌ | 自定义运算、显示、容器行为等 |
七、结语
Python 的面向对象特性赋予我们更强大的建模能力与代码组织方式。掌握类的基本构造、各种方法类型的语义与使用,是编写大型、可维护、高可读性程序的第一步。
更多推荐



所有评论(0)