How to write a package in Python

First of all, I need to describe what is to be done. Suppose we have two classes, namely the Person class and the Stu class. We want to pack these two classes into a package. It is that simple, so let's not talk too much nonsense, let us operate.

  • Step 1. Create a Package, named Demo1,
    right-click the project name -> new -> Python Package
    Insert picture description here
  • Step 2. Create the Person class under the Demo1 package
class Person:
    def __init__(self,name,gender):
        self.name = name
        self.gender =  gender
    def printinfo(self):
        print(self.name,self.gender)
  • Step 3. Create the Stu class under the Demo1 package
class Stu():
    def __init__(self,name,gender,stuid):
        self.name = name
        self.gender = gender
        self.stuid = stuid
    def printinfo(self):
        print(self.name,self.gender,self.stuid)

After completing the above steps, the directory structure should look like the following figure:
Insert picture description here

  • Step 3. If the IDE you are using is PyCharm, when you create a package, an __init__.py file will be automatically generated under this package. If you are not using PyCharm, you need to create the __init__.py file under Package. When there is an __init__.py file in a folder, Python considers this folder to be a package, __init__.py can be empty, or you can write some statements. Here we write some statements, which import the Person and Stu classes from the Person and Stu modules respectively, which means that once we import the Person and Stu modules, __init__.py will automatically import them for us. Person class and Stu class, so we can directly use these two classes.
    • Writing 1
    from .Person import Person
    from .Stu import Stu
    
    • Writing 2
    from Demo1.Person import Person
    from Demo1.Stu import Stu
    

At this point, a Python Package is created!

  • Step 4. Test, create test.py file under Demo1
from Demo1.Person import Person
from Demo1.Stu import Stu

if __name__ == '__main__':
    p = Person('djk','man')
    s = Stu('djk','man','nwnu')
    p.printinfo()
    s.printinfo()

Note! ! ! ! ! ! ! ! ! ! :
In the __init__.py file, we can use the following writing method:

from .Person import Person
from .Stu import Stu

This will not report an error; but if you use this way of writing in the test file or not in the __init__.py file, an error will be reported. If I use the above writing method in the test.py test file, the following error will be reported:
Insert picture description here
If you want to avoid this error, then don't be lazy, use absolute paths when importing packages or modules, and try not to use relative paths. ! !

Guess you like

Origin blog.csdn.net/dongjinkun/article/details/114591611