python package 的两种组织方式

简介: 方式一/package1/ .../__init__.py # 空文件   .../class1.py class Class1: def __init__(self): self.

 

方式一
/package1/

.../__init__.py

        # 空文件

 

.../class1.py

        class Class1:
            def __init__(self):
                self.name = "class one"
            
            def printInfo(self):
                print("i am class One!")


.../class2.py

        class Class2:
            def __init__(self):
                self.name = "class two"
            
            def printInfo(self):
                print("i am class two!")


/demo1.py

    from package1.class1 import Class1
    from package1.class2 import Class2

    if __name__ == "__main__":
        c1 = Class1()
        c1.printInfo()
        c2 = Class2()
        c2.printInfo()

 



#####################################

方式二

/package2/
.../__init__.py

        from .class1 import Class1
        from .class2 import Class2

 

... /class1.py

        class Class1:
            def __init__(self):
                self.name = "class one"
            
            def printInfo(self):
                print("i am class One!")


.../class2.py

        class Class2:
            def __init__(self):
                self.name = "class two"
            
            def printInfo(self):
                print("i am class two!")

 

/demo2.py

    from package2 import Class1, Class2

    if __name__ == "__main__":
        c1 = Class1()
        c1.printInfo()
        c2 = Class2()
        c2.printInfo()

 




 

目录
相关文章
|
3月前
|
Python
【Python】解决Can‘t find model ‘en‘. It doesn‘t seem to be a shortcut link, a Python package or a valid
在使用以下代码时,报错Can’t find model ‘en’. It doesn’t seem to be a shortcut link, a Python package or a valid path to a data directory.
55 1
|
5月前
|
Python
Python中的模块对象__package__
【6月更文挑战第13天】
38 5
|
Python
Python常见问题 - pip报错 ValueError: Unable to find resource t64.exe in package pip._vendor.distlib
Python常见问题 - pip报错 ValueError: Unable to find resource t64.exe in package pip._vendor.distlib
429 0
Python常见问题 - pip报错 ValueError: Unable to find resource t64.exe in package pip._vendor.distlib
Python 编程 | 连载 19 - Package 和 Module
Python 编程 | 连载 19 - Package 和 Module
Python 编程 | 连载 19 - Package 和 Module
|
Python
Python 常见问题 - 使用 poetry build 打包构建失败,报 ModuleOrPackageNotFound No file/folder found for package filesystemfastapi
Python 常见问题 - 使用 poetry build 打包构建失败,报 ModuleOrPackageNotFound No file/folder found for package filesystemfastapi
353 0
Python 常见问题 - 使用 poetry build 打包构建失败,报 ModuleOrPackageNotFound No file/folder found for package filesystemfastapi
下一篇
无影云桌面