__init__文件和__init__函数

本文详细解释了Python中__init__.py文件的作用及其如何使Python将目录视为包的一部分,避免命名冲突并简化模块导入过程。同时介绍了__init__方法的功能,它作为构造函数,在创建类实例时自动调用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前言

时常看到__init__ 这个字眼,项目文档结构会出现__init__.py 文件,python文件中会看到def __init(): 函数,对其总是一知半解。今天,细查了资料,对其做个系统的认识。

__init__.py 文件

引用stackoverflow的两个回答。
引用1:

The__init__.py files are required to make Python treat the directories as containing packages; this is done to prevent directories with a common name, such as string, from unintentionally hiding valid modules that occur later (deeper) on the module search path. In the simplest case,__init__.py can just be an empty file, but it can also execute initialization code for the package or set the__all__variable, described later.

引用2:

Files named__init__.py are used to mark directories on disk as Python package directories. If you have the files

mydir/spam/__init__.py
mydir/spam/module.py

and mydir is on your path, you can import the code in module.py as

import spam.module

or

from spam import module

If you remove the__init__.pyfile, Python will no longer look for submodules inside that directory, so attempts to import the module will fail.

The__init__.pyfile is usually empty, but can be used to export selected portions of the package under more convenient name, hold convenience functions, etc. Given the example above, the contents of the init module can be accessed as

import spam

上面的两个引用就说明了__init__.py 文件的作用:
让python把当前文件夹当成是一个内含的包。

  • 防止新建的python文件和包里面的文件重名;
  • 方便导包

__init__(self) 函数

看个例子:

class A(object):
    def __init__(self):
        self.x = 'Hello'

    def method_a(self, foo):
        print(self.x + ' ' + foo)

a = A()     # We do not pass any argument to the __init__ method
a.method_a('Sailor!') # We only pass a single argument

__init__ 方法 在python相当于一个构造函数,当实例a创建后,自动就执行了__init__ 方法,并把self作为它的第一个参数。

我们没有专门调用__init__方法,只是在创建一个类的新实例的时候,把参数包含在圆括号内跟在类名后面,从而传递给__init__方法。

注:self 相当于对象的实例

另一个实例帮助理解:

class MyClass(object):
     i = 123
     def __init__(self):
         self.i = 345

a = MyClass()
print(a.i)
345
print(MyClass.i)
123

资料来源

  1. What is__init__.py for?
  2. __init__方法
  3. Python __init__ and self what do they do?
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值