当前位置:   article > 正文

python类、模块的初始化——__init___python 模块初始化

python 模块初始化
1.类中的__init__

__ init __ 为类的初始化函数,当声明类后,要有__init__对类进行初始化。

可以有如下两种方式

class test:
    def __init__(self):
        self.name = None
  • 1
  • 2
  • 3
'
运行
class test:
    def __init__(self,name):
        self.name = name
  • 1
  • 2
  • 3

当使用类的时候,会自动调用__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"`在这里插入代码片`
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

当定义类test后,.score为输入值

a=ts.test(80)
  • 1

自动运行内容,生成test.rank和test.grand。

a.rank
8.0
  • 1
  • 2

a.getrank()
8.0
  • 1
  • 2
  • 3
2.模块中的__init__

python的包有不同的结构层次,在调用包的时候,经常需要__init__对于包进行初始化。

当使用import后,会对于文件夹下的内容进行自动运行,最常用的情况是__init__设置为空白。模块ecog结构如下:

–ecog
|-__ init__.py -----------(1)
|-units.py
|-addtest
||-__ init__.py ----------(2)
||-analysis.py

在结构中有两个__init__文件,我们先考虑前一个。

(1)
1. 基本性质

ecog模块的初始化函数,当为空白文件时,import后,不可直接调用内部模块units。如下;

import ecog
ecog.units
  • 1
  • 2

输出为

AttributeError: 'module' object has no attribute 'units'
  • 1

对应的需要分别导入

import ecog.units
  • 1

可以得到对应模块

 <module 'ecog.units' from '/home/sunkj/anaconda3/envs/python27/lib/python2.7/site-packages/ecog/units.pyc'>
  • 1

对于文件,在没有__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'>
  • 1
  • 2
  • 3
  • 4
2. 进阶操作

可以在__init__.py中加入一些语句,在调用时即可运行这些语句,可以便于更方便的进行其中的包的调用。

如,在(1)里加入,

import units
  • 1

即可跳过指定的导入

import ecog

ecog.units
 <module 'ecog.units' from '/home/sunkj/anaconda3/envs/python27/lib/python2.7/site-packages/ecog/units.pyc'>
  • 1
  • 2
  • 3
  • 4

如果直接在 __init__.py中加入特定函数,(可用from x import *)

from units import test_LME
  • 1

即可直接完成对于指定函数的初始化:

import ecog

ecog.test_LME
<function ecog.units.test_LME>
  • 1
  • 2
  • 3
  • 4

在此情况下,也使用getattr可有更多简便的操作,

getattr(ecog,'test_LME')

 <function ecog.units.test_LME>
  • 1
  • 2
  • 3

getatter用于差找后一个属性是不是存在于前一个模块当中,并进行赋值,这种方法可用于对于文件夹中有多种操作的调用。

附:

__all__也可用于初始化,写在__init__.py函数当中,此时进行默认导入的时候可以只将__all__里的元素导入。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/笔触狂放9/article/detail/964158
推荐阅读
相关标签
  

闽ICP备14008679号