__init__文件和__init__函數


前言

時常看到__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?

注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
粤ICP备14056181号  © 2014-2020 ITdaan.com