全部学科
Python全栈
python
NodeJS全栈
nodejs
小程序首页
📅 2026-05-19 10 分钟 ✍️ juanwangdev

Python 类与对象基础

类定义对象的模板,包含属性和方法;对象是类的实例。

定义类与创建实例

Python
class Person:
    "简单的类定义"

    def __init__(self, name, age):
        self.name = name
        self.age = age

    def introduce(self):
        return f"我是 {self.name}, {self.age} 岁"


# 创建实例
p1 = Person("Alice", 25)
p2 = Person("Bob", 30)

print(p1.introduce())  # 我是 Alice, 25 岁
print(p2.introduce())  # 我是 Bob, 30 岁

类属性与实例属性

Python
class Student:
    # 类属性:所有实例共享
    school = "北京大学"
    count = 0

    def __init__(self, name):
        # 实例属性:每个实例独立
        self.name = name
        Student.count += 1


s1 = Student("Alice")
s2 = Student("Bob")

# 类属性访问
print(Student.school)  # 北京大学
print(s1.school)       # 北京大学(通过实例访问)
print(s2.school)       # 北京大学

# 实例属性访问
print(s1.name)         # Alice
print(s2.name)         # Bob

# 类属性统计实例数
print(Student.count)   # 2

属性查找顺序

Python
访问 obj.attr:

1. 实例 __dict__['attr']
2. 类 __dict__['attr']
3. 父类 __dict__['attr'](继承链)
4. __getattr__(不存在时触发)

避免类属性陷阱

Python
class Counter:
    count = 0

    def increment(self):
        # 错误:这会创建实例属性,而非修改类属性
        self.count += 1


c = Counter()
c.increment()
print(c.count)       # 1(实例属性)
print(Counter.count) # 0(类属性未变)

# 正确:直接修改类属性
class Counter2:
    count = 0

    def increment(self):
        Counter2.count += 1


c2 = Counter2()
c2.increment()
print(Counter2.count)  # 1(类属性已变)

属性存储位置

Python
class MyClass:
    class_attr = "类属性"

    def __init__(self):
        self.instance_attr = "实例属性"


obj = MyClass()

# 类属性在类 __dict__ 中
print(MyClass.__dict__['class_attr'])  # 类属性

# 实例属性在实例 __dict__ 中
print(obj.__dict__['instance_attr'])   # 实例属性

# 实例不存储类属性
print(obj.__dict__)  # {'instance_attr': '实例属性'}

self 参数

self 表示实例对象本身:

Python
class Book:
    def __init__(self, title):
        self.title = title  # self.title 是实例属性

    def get_title(self):
        return self.title  # 通过 self 访问实例属性


b = Book("Python教程")
b.get_title()  # Python教程

方法类型

实例方法

Python
class Calculator:
    def __init__(self, value):
        self.value = value

    def add(self, num):  # 实例方法
        self.value += num
        return self.value


calc = Calculator(10)
print(calc.add(5))  # 15

类方法

Python
class Factory:
    count = 0

    @classmethod
    def create(cls):  # cls 是类本身
        cls.count += 1
        return cls(cls.count)

    def __init__(self, id):
        self.id = id


f1 = Factory.create()
f2 = Factory.create()
print(f1.id)  # 1
print(f2.id)  # 2
print(Factory.count)  # 2

静态方法

Python
class Utility:
    @staticmethod
    def add(a, b):  # 不需要 self 或 cls
        return a + b


print(Utility.add(1, 2))  # 3

u = Utility()
print(u.add(3, 4))  # 7
方法类型第一个参数调用方式
实例方法self(实例)obj.method()
类方法cls(类)cls.method()obj.method()
静态方法cls.method()obj.method()

initnew

Python
class Demo:
    def __new__(cls, *args, **kwargs):
        print("__new__ 创建实例")
        instance = super().__new__(cls)
        return instance

    def __init__(self, value):
        print("__init__ 初始化实例")
        self.value = value


d = Demo(10)
# __new__ 创建实例
# __init__ 初始化实例
方法作用返回值
__new__创建实例对象实例对象
__init__初始化实例属性None

动态添加属性与方法

Python
class Dynamic:
    pass


d = Dynamic()

# 动态添加实例属性
d.name = "动态"
print(d.name)  # 动态

# 动态添加实例方法
def greet(self):
    return f"Hello, {self.name}"


import types
d.greet = types.MethodType(greet, d)
print(d.greet())  # Hello, 动态

# 动态添加类属性
Dynamic.class_attr = "类属性"
print(d.class_attr)  # 类属性

类的组成

Python
class Person:
    "人的类"

    species = "人类"  # 类属性

    def __init__(self, name):
        self.name = name  # 实例属性

    def say(self):
        "实例方法"
        return f"{self.name}说话"

    @classmethod
    def get_species(cls):
        "类方法"
        return cls.species

    @staticmethod
    def is_alive():
        "静态方法"
        return True


# 查看类组成
print(Person.__dict__)
# {'__module__': ..., '__init__': <function>, 'say': <function>, ...}

# 查看实例组成
p = Person("Alice")
print(p.__dict__)  # {'name': 'Alice'}

isinstance 与 issubclass

Python
class Animal:
    pass


class Dog(Animal):
    pass


d = Dog()

print(isinstance(d, Dog))      # True
print(isinstance(d, Animal))   # True
print(issubclass(Dog, Animal)) # True
print(issubclass(Animal, Dog)) # False

type 函数

text
class MyClass:
    pass


obj = MyClass()

print(type(obj))      # MyClass
print(type(obj) is MyClass)  # True

# 动态创建类
DynamicClass = type('DynamicClass', (), {'attr': 'value'})
print(DynamicClass.attr)  # value

要点总结

要点说明
类属性定义在类中,所有实例共享
实例属性定义在 __init__ 中,每个实例独立
self实例方法的第一个参数,表示实例本身
cls类方法的第一个参数,表示类本身
__dict__存储属性和方法的字典

类属性在类 __dict__,实例属性在实例 __dict__,实例先查找自己的字典,再查找类的字典。

D:\git2\jwdev\articles\PYTHON\进阶\面向对象编程\类与对象基础.md

📝 发现内容有误?点击此处直接编辑

← 上一篇 Python 私有属性与方法
下一篇 → Python 继承机制
想查看更多题目和详细解析?
小程序提供完整的题库、模拟考试和详细解析
马上就来

长按或扫描二维码,立即体验

扫码体验小程序
马上就来
使用微信扫描二维码
立即体验完整题库