用Python写一个简单的包

每次写Python的时候,我们开头一般都要导入一些安装的包,有的是import xxx,有的是from xxx import yyy,对这些导入我一直都是一知半解,于是希望通过自己写一个简单的包来进一步理解包的导入。

第一步:新建一个文件夹,命名为Animals,这个文件夹就是我们要导入的包的名字。

第二步:在Animals文件夹下新建两个python文件Mammals.py和Birds.py,内容如下:

# Mammals.py
class Mammals:
    def __init__(self):
        '''constructor for this class.'''
        # Create some member animals
        self.members = ['Tiger', 'Elephant', 'Wild Cat']

    def printMembers(self):
        print('Printing members of the Mammals class')
        for member in self.members:
            print('\t{}'.format(member))
# Birds.py
class Birds:
    def __init__(self):
        ''' Constructor for this class. '''
        # Create some member animals
        self.members = ['Sparrow', 'Robin', 'Duck']

    def printMembers(self):
        print('Printing members of the Birds class')
        for member in self.members:
            print('\t{}'.format(member))

第三步:在Animals文件夹下新建__init__.py文件,当一个文件夹下有这个__init__.py文件时,python认为这个文件夹是一个包,__init__.py可以为空,也可以写入一些语句。这里我们写入一些语句,该语句分别从Mammals和Birds两个模块(modules)里导入Mammals和Birds类,也就是说一旦我们导入Mammals和Birds这两个模块,__init__.py会自动帮我们导入Mammals和Birds类,从而我们可以直接使用这两个类。

# __init__.py
from .Mammals import Mammals
from .Birds import Birds

到此,第一个python包就建好了。

我们在Animals这个文件夹所在的文件夹下创建一个Animals_test.py文件,来导入这个包进行测试:

# Animals_test.py
# Import classes from your brand new package
from Animals import Mammals
from Animals import Birds

# Create an object of Mammals class & call a method of it
myMammal = Mammals()
myMammal.printMembers()

# Create an object of Birds class & call a method of it
myBird = Birds()
myBird.printMembers()

 我们还可以用另一种写法:

# Animals_test.py
# Import classes from your brand new package
import Animals
# Create an object of Mammals class & call a method of it
myMammal = Animals.Mammals()
myMammal.printMembers()

# Create an object of Birds class & call a method of it
myBird = Animals.Birds()
myBird.printMembers()

 

参考链接:

[1] https://www.pythoncentral.io/how-to-create-a-python-package/

posted @ 2019-05-24 23:04  小飞的学习笔记  阅读(3842)  评论(0编辑  收藏  举报