赞
踩
__ init __ 为类的初始化函数,当声明类后,要有__init__对类进行初始化。
可以有如下两种方式
class test:
def __init__(self):
self.name = None
class test:
def __init__(self,name):
self.name = name
当使用类的时候,会自动调用__init __函数,运行其内容。
如以下,定义类
class test(object):
def __init__(self,score):
self.score=score
self.rank=self.getrank()
self.grand=self.getgrand()
def getrank(self):
rank=self.score/10
return rank
def getgrand(self):
if self.score >= 80:
return "A"
elif self.score >= 70:
return "B"
else:
return "C"`在这里插入代码片`
当定义类test后,.score为输入值
a=ts.test(80)
自动运行内容,生成test.rank和test.grand。
a.rank
8.0
a.getrank()
8.0
python的包有不同的结构层次,在调用包的时候,经常需要__init__
对于包进行初始化。
当使用import
后,会对于文件夹下的内容进行自动运行,最常用的情况是__init__
设置为空白。模块ecog
结构如下:
–ecog
|-__ init__.py -----------(1)
|-units.py
|-addtest
||-__ init__.py ----------(2)
||-analysis.py
在结构中有两个__init__文件,我们先考虑前一个。
为ecog
模块的初始化函数,当为空白文件时,import
后,不可直接调用内部模块units
。如下;
import ecog
ecog.units
输出为
AttributeError: 'module' object has no attribute 'units'
对应的需要分别导入
import ecog.units
可以得到对应模块
<module 'ecog.units' from '/home/sunkj/anaconda3/envs/python27/lib/python2.7/site-packages/ecog/units.pyc'>
对于文件,在没有__init__.py
的情况下,无法导入,当有(2)的__init__.py
文件时,不需导入即可调用。
import ecog
ecog.addtest
<module 'ecog.addtest' from '/home/sunkj/anaconda3/envs/python27/lib/python2.7/site-packages/ecog/addtest/__init__.py'>
可以在__init__.py
中加入一些语句,在调用时即可运行这些语句,可以便于更方便的进行其中的包的调用。
如,在(1)里加入,
import units
即可跳过指定的导入
import ecog
ecog.units
<module 'ecog.units' from '/home/sunkj/anaconda3/envs/python27/lib/python2.7/site-packages/ecog/units.pyc'>
如果直接在 __init__.py
中加入特定函数,(可用from x import *
)
from units import test_LME
即可直接完成对于指定函数的初始化:
import ecog
ecog.test_LME
<function ecog.units.test_LME>
在此情况下,也使用getattr
可有更多简便的操作,
getattr(ecog,'test_LME')
<function ecog.units.test_LME>
getatter
用于差找后一个属性是不是存在于前一个模块当中,并进行赋值,这种方法可用于对于文件夹中有多种操作的调用。
__all__
也可用于初始化,写在__init__.py
函数当中,此时进行默认导入的时候可以只将__all__
里的元素导入。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。