__init__文件和__init__函数
来源:互联网 发布:抽奖活动中奖概率算法 编辑:程序博客网 时间:2024/06/05 09:59
前言
时常看到__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 filesmydir/spam/
__init__.py
mydir/spam/module.pyand 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__.py
file, Python will no longer look for submodules inside that directory, so attempts to import the module will fail.The
__init__.py
file 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 asimport 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__ methoda.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 = 345a = MyClass()print(a.i)345print(MyClass.i)123
资料来源
- What is
__init__.py
for? __init__
方法Python __init__ and self what do they do?
- __init__文件和__init__函数
- Python中的__init__()和__call()__函数
- python中的“__init__”函数
- __init__.py文件作用
- __init__.py 包文件
- python __init__.py文件
- Python__new__和__init__
- __new__ 和 __init__
- python __new__ 和 __init__
- python __init__ 和 setter
- python __new__和__init__
- __new__ ,__init__和__del__
- python __init__构造函数 和 __del__析构函数
- python __call__ 函数 __init__ 对比
- Python类中__init__函数和self参数的关系
- __init__.py 文件的作用
- __init__.py 文件的作用
- __init__.py文件的作用
- <模板>(Miller-Rabin和Pollard_rho算法)poj 2429 GCD & LCM Inverse (数论)
- 题解:3Sum Closest
- java socket 通信详解
- 动态规划--鸣人的影分身
- 未解决 训练赛3 ,kmp || 字符串哈希(没学)Censor SCU
- __init__文件和__init__函数
- leetcode第七周解题总结
- tyvj 1080 N皇后
- k-近邻算法
- O..One..One...Day
- android 源码repo下载方式
- 腾讯云Ubuntu16.04下搭建Java开发环境(工具,JDK,Eclipse,MySQL,Tomcat)
- 并查集详解 (转)
- 笔试面试算法经典-打印n个数组中最大的topk