代码布局:
mypackage/human.py
1
2
3
4
5
6
7
8
9
10
11
12
|
#!/usr/bin/env python class person: def __init__( self ,name,age,sex): self .name = name self .age = age self .sex = sex def sayHello( self ,msg = 'Hello' ): print (msg) def printInfo( self ): print ( 'name:' + self .name + ' age:' + str ( self .age) + ' sex:' + self .sex ) |
mypackage/student.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
#!/usr/bin/env python from mypackage.human import person class student(person): def __init__( self ,name,age,sex,stuid,score): person.__init__( self ,name,age,sex) self .stuid = stuid self .score = score def sayHi( self ,msg = 'Hi' ): print (msg) def printInfo( self ): person.printInfo( self ) print ( 'stuid:' + str ( self .stuid) + ' score:' + str ( self .score) ) |
test.py
1
2
3
4
5
6
7
8
9
10
11
12
|
#!/usr/bin/env python from mypackage.human import person from mypackage.student import student per = person( 'person' , 24 , 'man' ) per.sayHello() per.printInfo() stu = student( 'xiaodaima' , 23 , 'man' , 1001 , 100 ) stu.sayHi() stu.printInfo() |
运行效果:
1
2
3
4
5
6
7
|
[laolang@localhost packagetest]$ . /test .py Hello name:person age:24 sex: man Hi name:xiaodaima age:23 sex: man stuid:1001 score:100 [laolang@localhost packagetest]$ |
自定义的包中,必须有__init__.py文件
在自定义包的时候,如果要引入其它包,则使用from import就可以。