python自己写包_用Python写一个简单的包

本文通过实例介绍了如何创建一个Python包,包括新建包含__init__.py的文件夹、编写模块和在__init__.py中导入类。然后在Animals_test.py中导入并测试了包中的Mammals和Birds类,展示了两种导入方式。
摘要由CSDN通过智能技术生成

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

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

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

#Mammals.py

classMammals:def __init__(self):'''constructor for this class.'''

#Create some member animals

self.members = ['Tiger', 'Elephant', 'Wild Cat']defprintMembers(self):print('Printing members of the Mammals class')for member inself.members:print('\t{}'.format(member))

#Birds.py

classBirds:def __init__(self):'''Constructor for this class.'''

#Create some member animals

self.members = ['Sparrow', 'Robin', 'Duck']defprintMembers(self):print('Printing members of the Birds class')for member inself.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 importMammalsfrom .Birds import Birds

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

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

#Animals_test.py#Import classes from your brand new package

from Animals importMammalsfrom Animals importBirds#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

importAnimals#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()

参考链接:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值