飞翔飞翔
主页
  • 计算机基础

    • TCP/IP协议
    • Linux命令
  • 数据库

    • SQL教程
  • 编程语言

    • C语言
    • Python2
    • Python3
  • 数据格式

    • JSON教程
  • 工具

    • Markdown指南
  • Git

    • GitFlow
  • Quartz

    • Quartz教程
  • Java

    • Java设计模式
  • 缓存

    • Redis教程
联系
阿里云
主页
  • 计算机基础

    • TCP/IP协议
    • Linux命令
  • 数据库

    • SQL教程
  • 编程语言

    • C语言
    • Python2
    • Python3
  • 数据格式

    • JSON教程
  • 工具

    • Markdown指南
  • Git

    • GitFlow
  • Quartz

    • Quartz教程
  • Java

    • Java设计模式
  • 缓存

    • Redis教程
联系
阿里云
  • 学习路径
  • 第1章 认识Python

    • Python 历史与特点
    • Python 2 与 Python 3 的核心差异
    • 安装与运行 Python 2.7.18
    • 编码规范 PEP 8
  • 第2章 基础语法

    • 变量与对象
    • 数字类型
    • 字符串 str
    • Unicode 字符串
    • 运算符
    • 空值 None
  • 第3章 流程控制

    • if 条件语句
    • if-else 条件语句
    • if-elif-else 多分支
    • 条件表达式(三元运算符)
    • while 循环
    • for 循环
    • range 与 xrange
    • 循环控制:break、continue、pass
    • 循环 else 子句
  • 第4章 数据结构

    • 列表基础
    • 列表方法
    • 列表推导式
    • 元组
    • 字典基础
    • 字典方法
    • 字典循环技巧
    • 集合
    • 序列解包
    • 序列比较
  • 第5章 函数

    • 定义函数
    • 参数传递机制
    • 默认参数
    • 关键字参数
    • 可变参数
    • Lambda 表达式
    • 文档字符串
    • 函数对象
  • 第6章 模块与包

    • import 导入
    • 模块搜索路径
    • name 与主程序
    • 编译文件 .pyc 与 .pyo
    • 包结构
    • dir() 函数
  • 第7章 文件与IO

    • 打开与关闭文件
    • 文件读写方法
    • with 上下文管理器
    • 格式化输出:% 操作符
    • 格式化输出:str.format()
    • JSON 序列化
  • 第8章 面向对象

    • 类定义与实例化
    • init 构造方法
    • 类变量与实例变量
    • 方法调用与 self
    • 继承基础
    • 多重继承
    • 新式类与旧式类
    • 私有变量与名称改写
    • 属性装饰器 property
    • 类方法与静态方法
    • 魔术方法
    • 空类与数据记录
  • 第9章 异常处理

    • 异常类型
    • try-except
    • try-except-else-finally
    • 抛出异常 raise
    • 自定义异常
    • with 语句与上下文管理器
  • 第10章 迭代器与生成器

    • 迭代器协议
    • 生成器函数
    • 生成器表达式
    • itertools模块
  • 第11章 标准库精要

    • os模块
    • sys模块
    • datetime模块
    • re模块
    • json模块
    • collections模块
    • math与random模块
    • urllib2与网络请求
    • subprocess与命令执行
    • threading与并发
    • unittest与测试
    • 虚拟环境与包管理
  • 第12章 工程实践

    • 调试技巧
    • 性能分析
    • 文档与注释
    • 下一步学习

init 构造方法

__init__ 是 Python 类中最特殊的方法之一。它在实例创建后自动调用,用于初始化实例的属性。虽然名字里有 "init",但它不是构造函数(对象已经创建好了),而是初始化方法。

基本用法

class Person(object):
    def __init__(self, name, age):
        self.name = name
        self.age = age

p = Person("Alice", 25)
print p.name        # Alice
print p.age         # 25

__init__ 的第一个参数是 self(指向新创建的实例),后面可以跟任意数量的参数。创建实例时,Person("Alice", 25) 的参数会传递给 __init__。

self 参数

self 是实例本身的引用,必须作为第一个参数显式声明:

class Counter(object):
    def __init__(self):
        self.count = 0      # 给实例添加 count 属性
    
    def increment(self):
        self.count += 1     # 通过 self 访问实例属性
        return self.count

c = Counter()
print c.increment()     # 1
print c.increment()     # 2

调用 c.increment() 时,Python 自动把 c 作为第一个参数传给 self。所以 self.count 就是 c.count。

self 不是关键字,可以用其他名字,但强烈建议用 self——这是 Python 社区的约定,违反它会让代码难以阅读。

默认参数

__init__ 可以像普通函数一样使用默认参数:

class Person(object):
    def __init__(self, name, age=0, city="Unknown"):
        self.name = name
        self.age = age
        self.city = city

p1 = Person("Alice")
print p1.age, p1.city       # 0 Unknown

p2 = Person("Bob", 30, "Beijing")
print p2.age, p2.city       # 30 Beijing

p3 = Person("Charlie", city="Shanghai")
print p3.age, p3.city       # 0 Shanghai

参数验证

__init__ 中可以进行参数验证,确保对象创建时处于有效状态:

class Rectangle(object):
    def __init__(self, width, height):
        if width <= 0 or height <= 0:
            raise ValueError("Width and height must be positive")
        self.width = width
        self.height = height
        self.area = width * height

r = Rectangle(5, 3)
print r.area        # 15

r2 = Rectangle(-1, 3)     # ValueError: Width and height must be positive

没有 init 的类

如果类没有定义 __init__,实例创建后没有任何属性:

class Empty(object):
    pass

e = Empty()
print e.__dict__    # {},空字典

实例的属性存储在 __dict__ 字典中。__init__ 的作用就是往这个字典里添加初始值。

init 的返回值

__init__ 必须返回 None(隐式或显式)。如果返回其他值,会抛出 TypeError:

class Bad(object):
    def __init__(self):
        return 42         # TypeError: __init__() should return None

实际应用

银行账户:

class BankAccount(object):
    def __init__(self, owner, balance=0):
        self.owner = owner
        self.balance = balance
        self.transactions = []
    
    def deposit(self, amount):
        self.balance += amount
        self.transactions.append(("deposit", amount))
    
    def withdraw(self, amount):
        if amount > self.balance:
            raise ValueError("Insufficient funds")
        self.balance -= amount
        self.transactions.append(("withdraw", amount))

account = BankAccount("Alice", 100)
account.deposit(50)
account.withdraw(30)
print account.balance       # 120

配置对象:

class Config(object):
    def __init__(self, **kwargs):
        self.debug = kwargs.get("debug", False)
        self.host = kwargs.get("host", "localhost")
        self.port = kwargs.get("port", 8080)

config = Config(debug=True, port=3000)
print config.debug      # True
print config.host       # localhost
print config.port       # 3000
上一页
类定义与实例化
下一页
类变量与实例变量