• 用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('	{}'.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('	{}'.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/

  • 相关阅读:
    MySql插入查询的数据(命名Sql常用)
    odoo前端
    巧用 Odoo act_window 的 flags实现一些个性化的视图控制
    JDK安装
    2018年3月开始新的一年计划
    odoo10 api 装饰器
    odoo10 添加自动执行server action
    odoo中各组件的颜色及用法tree,kanban,many2many_tags,app_ui_enhance
    python virtualenv学习
    odoo10 fields.Selection 根据权限显示不同的selection内容
  • 原文地址:https://www.cnblogs.com/yunxiaofei/p/10920679.html
Copyright © 2020-2023  润新知