码迷,mamicode.com
首页 > 编程语言 > 详细

python3学习笔记--003--写一个自定义的包

时间:2015-08-25 17:08:34      阅读:146      评论:0      收藏:0      [点我收藏+]

标签:

代码布局:


[laolang@localhost packagetest]$ tree
.
├── mypackage
│   ├── human.py
│   ├── __init__.py
│   └── student.py
└── test.py

1 directory, 4 files
[laolang@localhost packagetest]$
mypackage/human.py



#!/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



#!/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



#!/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()
运行效果:



[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就可以,使用import怎么在自定义包中再引入其它的自定义包,暂时还不知道具体方法

python3学习笔记--003--写一个自定义的包

标签:

原文地址:http://my.oschina.net/iamhere/blog/496939

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!