Python中的类(Class)详解

@[toc]【Python】类(class)

【Python】类(class)

在 Python 中,类(Class) 是面向对象编程(OOP)的核心概念。类用于创建对象,对象是类的实例。类可以包含属性(变量)和方法(函数),用于描述对象的行为和状态。

Python 类的基本结构和用法:

1. 基本语法

class 类名:
    # 类属性(所有实例共享)
    类属性 = 值

    # 构造方法(初始化对象)
    def __init__(self, 参数1, 参数2, ...):
        # 实例属性(每个实例独有)
        self.属性1 = 参数1
        self.属性2 = 参数2

    # 实例方法
    def 方法名(self, 参数1, 参数2, ...):
        # 方法体
        pass

    # 类方法(使用 @classmethod 装饰器)
    @classmethod
    def 类方法名(cls, 参数1, 参数2, ...):
        # 方法体
        pass

    # 静态方法(使用 @staticmethod 装饰器)
    @staticmethod
    def 静态方法名(参数1, 参数2, ...):
        # 方法体
        pass

2. 示例:定义一个简单的类

class Dog:
    # 类属性
    species = "Canis familiaris"

    # 构造方法
    def __init__(self, name, age):
        # 实例属性
        self.name = name
        self.age = age

    # 实例方法
    def bark(self):
        return f"{self.name} says woof!"

    # 类方法
    @classmethod
    def get_species(cls):
        return f"Species: {cls.species}"

    # 静态方法
    @staticmethod
    def is_puppy(age):
        return age < 2

# 创建对象(实例化)
my_dog = Dog("Buddy", 3)

# 访问实例属性
print(my_dog.name)  # 输出: Buddy
print(my_dog.age)   # 输出: 3

# 调用实例方法
print(my_dog.bark())  # 输出: Buddy says woof!

# 调用类方法
print(Dog.get_species())  # 输出: Species: Canis familiaris

# 调用静态方法
print(Dog.is_puppy(1))  # 输出: True
print(Dog.is_puppy(3))  # 输出: False

3. 类的继承

继承是面向对象编程的重要特性,允许一个类继承另一个类的属性和方法。

# 父类
class Animal:
    def __init__(self, name):
        self.name = name

    def speak(self):
        return f"{self.name} makes a sound."

# 子类    继承于父类animal
class Cat(Animal):
    def speak(self):
        return f"{self.name} says meow!"

# 创建子类对象
my_cat = Cat("Whiskers")
print(my_cat.speak())  # 输出: Whiskers says meow!

4. 方法重写

子类可以重写父类的方法,以实现不同的行为。

class Bird(Animal):
    def speak(self):
        return f"{self.name} says chirp!"

my_bird = Bird("Tweety")
print(my_bird.speak())  # 输出: Tweety says chirp!

5. 多继承

Python 支持多继承,即一个类可以继承多个父类。

class A:
    def method(self):
        return "A"

class B:
    def method(self):
        return "B"

class C(A, B):
    pass

my_object = C()
print(my_object.method())  # 输出: A(遵循方法解析顺序 MRO)

6. 特殊方法(魔术方法)

Python 类可以通过定义特殊方法(以双下划线 __ 开头和结尾)来实现一些内置行为。

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    # 重写字符串表示
    def __str__(self):
        return f"Point({self.x}, {self.y})"

    # 重写加法操作
    def __add__(self, other):
        return Point(self.x + other.x, self.y + other.y)

# 使用
p1 = Point(1, 2)
p2 = Point(3, 4)
print(p1)          # 输出: Point(1, 2)
print(p1 + p2)     # 输出: Point(4, 6)

7. 类的属性和方法总结

==============================================================

  • 实例属性 每个对象独有的属性,通过 self.属性名 定义。
  • 类属性 所有对象共享的属性,直接在类中定义。
  • 实例方法 操作实例属性的方法,第一个参数是 self。
  • 类方法 操作类属性的方法,使用 @classmethod 装饰器,第一个参数是 cls。
  • 静态方法 与类和实例无关的方法,使用 @staticmethod 装饰器。
  • 8. 类的封装

    Python 通过命名约定来实现封装:

    公有属性/方法:直接定义(如 self.name)。

    私有属性/方法:以双下划线 __ 开头(如 self.__secret),外部无法直接访问。

    class BankAccount:
        def __init__(self, balance):
            self.__balance = balance  # 私有属性
    
        def deposit(self, amount):
            self.__balance += amount
    
        def get_balance(self):
            return self.__balance
    
    account = BankAccount(100)
    account.deposit(50)
    print(account.get_balance())  # 输出: 150
    # print(account.__balance)    # 报错:无法直接访问私有属性
    

    9. 类的 slots

    slots 用于限制类的实例属性,减少内存占用。

    class Person:
        __slots__ = ['name', 'age']
    
        def __init__(self, name, age):
            self.name = name
            self.age = age
    
    p = Person("Alice", 25)
    # p.address = "123 Street"  # 报错:无法添加未在 __slots__ 中定义的属性
    

    总结

    类是面向对象编程的核心,用于创建对象。

    类包含属性(实例属性和类属性)和方法(实例方法、类方法、静态方法)。

    支持继承、多继承、方法重写和特殊方法。

    通过命名约定实现封装。

    作者:shanks66

    物联沃分享整理
    物联沃-IOTWORD物联网 » Python中的类(Class)详解

    发表回复