1.类(Class)
在Python中类(Class)是面向对象编程(OOP)的核心概念。
1.1.类的基本定义
- 最简单的类
class Cat:"""这是一个最简单的类"""pass
#创建实例
obj = Cat()
- 包含方法的类
class Cat:"""这是一个最简单的类"""def bark(self):return "miao"def eat(self, food):return f"吃{food}"
#创建实例
obj = Cat()
1.2.构造方法__init__()
class Person:def __init__(self, name, age):"""构造方法,初始化示例属性"""self.name = nameself.age = ageself.is_adult = age >= 18def introduce(self):return f"我叫{self.name}, 今年{self.age}岁"#创建实例
person = Person("张三", 25)
print(person.introduce())
1.3.类属性和实例属性
class Car:#类属性wheels = 4country = "中国"def __init__(self, brand, color):#实例属性self.brand = brandself.color = colordef info(self):return f"{self.color}的{self.brand},有{self.wheels}个轮子"car = Car("丰田", "黑色")
print(car.info())
1.4.继承
类的继承可以包括单集成多集成,类定义后面括弧里面添加集成的父类
- 单继承
class Animal:def __init__(self, name):self.name = namedef speak(self):return "动物叫"class Dog(Animal):def __init__(self, name, breed):super().__init__(name)self.breed = breeddef speak(self):return "旺旺"def fetch(self):return f"{self.name}在接飞盘"#使用
dog = Dog("小黑", "拉布拉多")
print(dog.speak())
print(dog.fetch())
print(dog.name)
- 多继承
class Flyable:def fly(self):return "我能飞"class Swimmable:def swim(self):return "我能游泳"class Duck(Flyable, Swimmable): # 多继承def __init__(self, name):self.name = namedef quack(self):return "嘎嘎!"# 使用
duck = Duck("唐老鸭")
print(duck.quack()) # 输出: 嘎嘎!
print(duck.fly()) # 输出: 我能飞
print(duck.swim()) # 输出: 我能游泳
1.5.封装-访问控制
使用命名约定
class BankAccount:def __init__(self, owner, balance=0):self.owner = owner # 公开属性self._balance = balance # 受保护属性(约定)self.__password = "123456" # 私有属性(名称修饰)def deposit(self, amount):"""存款"""if amount > 0:self._balance += amountreturn Truereturn Falsedef withdraw(self, amount):"""取款"""if 0 < amount <= self._balance:self._balance -= amountreturn Truereturn Falsedef get_balance(self):"""获取余额(公开方法)"""return self._balancedef _internal_method(self):"""受保护方法"""return "内部方法"def __private_method(self):"""私有方法"""return "私有方法"# 使用
account = BankAccount("张三", 1000)
print(account.owner) # 输出: 张三
print(account.get_balance()) # 输出: 1000# 仍然可以访问(但不应该)
print(account._balance) # 输出: 1000
# print(account.__password) # 错误:AttributeError
1.6类方法和静态方法
class MathUtils:# 类属性PI = 3.14159@classmethoddef circle_area(cls, radius):"""类方法:计算圆面积"""return cls.PI * radius ** 2@staticmethoddef add(a, b):"""静态方法:加法"""return a + bdef instance_method(self):"""实例方法"""return "实例方法"# 使用
print(MathUtils.circle_area(5)) # 输出: 78.53975
print(MathUtils.add(3, 4)) # 输出: 7# 也可以通过实例调用
utils = MathUtils()
print(utils.circle_area(3)) # 输出: 28.27431
1.7使用示例
class Student:def __init__(self, name, student_id):self.name = nameself.student_id = student_idself.courses = {} # 课程字典 {课程名: 成绩}self.gpa = 0.0def enroll_course(self, course_name):"""选课"""if course_name not in self.courses:self.courses[course_name] = Nonereturn Truereturn Falsedef update_grade(self, course_name, grade):"""更新成绩"""if course_name in self.courses and 0 <= grade <= 100:self.courses[course_name] = gradeself._calculate_gpa()return Truereturn Falsedef _calculate_gpa(self):"""计算GPA(私有方法)"""valid_grades = [g for g in self.courses.values() if g is not None]if valid_grades:self.gpa = sum(valid_grades) / len(valid_grades)def get_info(self):"""获取学生信息"""return {'name': self.name,'student_id': self.student_id,'courses': self.courses.copy(),'gpa': self.gpa}def __str__(self):return f"学生{self.name}(学号:{self.student_id})"class StudentManager:def __init__(self):self.students = {}def add_student(self, name, student_id):"""添加学生"""if student_id not in self.students:self.students[student_id] = Student(name, student_id)return Truereturn Falsedef get_student(self, student_id):"""获取学生"""return self.students.get(student_id)def remove_student(self, student_id):"""删除学生"""if student_id in self.students:del self.students[student_id]return Truereturn False# 使用示例
manager = StudentManager()
manager.add_student("张三", "2023001")
manager.add_student("李四", "2023002")student = manager.get_student("2023001")
student.enroll_course("数学")
student.enroll_course("英语")
student.update_grade("数学", 85)
student.update_grade("英语", 92)print(student.get_info())
1.8抽象基类
from abc import ABC, abstractmethodclass Shape(ABC): # 抽象基类@abstractmethoddef area(self):"""计算面积"""pass@abstractmethoddef perimeter(self):"""计算周长"""passclass Rectangle(Shape):def __init__(self, width, height):self.width = widthself.height = heightdef area(self):return self.width * self.heightdef perimeter(self):return 2 * (self.width + self.height)# 使用
rect = Rectangle(5, 3)
print(f"面积: {rect.area()}") # 输出: 面积: 15
print(f"周长: {rect.perimeter()}") # 输出: 周长: 16# shape = Shape() # 错误:不能实例化抽象类
2.方法(Method)
2.1.方法类型
方法的类型分为示例方法、类方法、静态方法
- 实例方法
class Calculator:def add(self, a, b): # self是必须的第一个参数"""实例方法:加法"""return a + bdef multiply(self, a, b):"""实例方法:乘法"""return a * b# 使用
calc = Calculator()
result = calc.add(5, 3) # 输出: 8
print(result)
通过使用注解@classmethod
- 类方法
class MathUtils:PI = 3.14159@classmethoddef circle_area(cls, radius): # cls代表类本身"""类方法:计算圆面积"""return cls.PI * radius ** 2@classmethoddef set_pi(cls, new_pi):"""修改类属性"""cls.PI = new_pi# 使用
print(MathUtils.circle_area(5)) # 通过类调用: 78.53975
print(MathUtils.PI) # 输出: 3.14159MathUtils.set_pi(3.14)
print(MathUtils.circle_area(5)) # 输出: 78.5
- 静态方法
通过使用@staticmethod
class StringUtils:@staticmethoddef reverse_string(s):"""静态方法:反转字符串"""return s[::-1]@staticmethoddef is_palindrome(s):"""检查是否是回文"""return s == s[::-1]# 使用
print(StringUtils.reverse_string("hello")) # 输出: olleh
print(StringUtils.is_palindrome("radar")) # 输出: True# 也可以通过实例调用
utils = StringUtils()
print(utils.reverse_string("world")) # 输出: dlrow
2.2.方法参数
- 位置参数
class User:def register(self, username, password, email):"""位置参数"""self.username = usernameself.password = passwordself.email = emailuser = User()
user.register("alice", "secret", "alice@email.com")
- 默认参数
class User:def register(self, username, password, email, is_active=True, role="user"):"""带默认值的参数"""self.username = usernameself.password = passwordself.email = emailself.is_active = is_activeself.role = roleuser = User()
user.register("bob", "password", "bob@email.com") # 使用默认值
user.register("admin", "admin123", "admin@email.com", False, "admin")
- 关键字参数
class Config:def set_config(self, **kwargs):"""关键字参数"""for key, value in kwargs.items():setattr(self, key, value)config = Config()
config.set_config(host="localhost", port=8080, debug=True)
print(config.host) # 输出: localhost
- 可变位置参数
class Calculator:def sum_all(self, *args):"""可变位置参数"""return sum(args)def average(self, *args):"""计算平均值"""if not args:return 0return sum(args) / len(args)calc = Calculator()
print(calc.sum_all(1, 2, 3, 4, 5)) # 输出: 15
print(calc.average(10, 20, 30)) # 输出: 20.0
2.3.特殊方法
- 构造和析构方法
class FileHandler:def __init__(self, filename):"""构造方法"""self.filename = filenameself.file = open(filename, 'r')print(f"文件 {filename} 已打开")def __del__(self):"""析构方法"""if hasattr(self, 'file') and self.file:self.file.close()print(f"文件 {self.filename} 已关闭")# 使用
handler = FileHandler("test.txt")
# 当对象被销毁时自动调用__del__
- 字符串表示方法
class Person:def __init__(self, name, age):self.name = nameself.age = agedef __str__(self):"""用户友好的字符串表示"""return f"Person: {self.name}, {self.age}岁"def __repr__(self):"""开发者的字符串表示"""return f"Person('{self.name}', {self.age})"person = Person("张三", 25)
print(str(person)) # 输出: Person: 张三, 25岁
print(repr(person)) # 输出: Person('张三', 25)
- 运算符重载方法
class Vector:def __init__(self, x, y):self.x = xself.y = ydef __add__(self, other):"""加法运算符重载"""return Vector(self.x + other.x, self.y + other.y)def __sub__(self, other):"""减法运算符重载"""return Vector(self.x - other.x, self.y - other.y)def __mul__(self, scalar):"""乘法运算符重载"""return Vector(self.x * scalar, self.y * scalar)def __eq__(self, other):"""相等运算符重载"""return self.x == other.x and self.y == other.yv1 = Vector(2, 3)
v2 = Vector(1, 2)
v3 = v1 + v2 # Vector(3, 5)
v4 = v1 * 2 # Vector(4, 6)
print(v3.x, v3.y) # 输出: 3 5
方法类型 | 装饰器 | 第一个参数 | 用途 |
---|---|---|---|
实例方法 | 无 | self | 操作实例数据 |
类方法 | @classmethod | cls | 操作类属性 |
静态方法 | @staticmethod | 无 | 工具函数 |
属性方法 | @property | self | 像属性一样访问 |
抽象方法 | @abstractmethod | self/cls | 定义接口 |