用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/


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM