IT博客汇
  • 首页
  • 精华
  • 技术
  • 设计
  • 资讯
  • 扯淡
  • 权利声明
  • 登录 注册

    python学习之路之实例学习003–写一个自定义的包

    Vlix_Liu发表于 2015-12-06 15:59:12
    love 0

    代码布局:

     

     
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    [laolang@localhost packagetest]$ tree
    .
    ├── mypackage
    │   ├── human.py
    │   ├── __init__.py
    │   └── student.py
    └── test.py
    1 directory, 4 files
    [laolang@localhost packagetest]$

    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就可以。



沪ICP备19023445号-2号
友情链接