__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 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__ 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

资料来源

  1. What is__init__.py for?
  2. __init__方法
  3. Python __init__ and self what do they do?
1 0
原创粉丝点击