python基础5-阿里云开发者社区

开发者社区> 技术小甜> 正文

python基础5

简介:
+关注继续查看

模块

 

什么是模块:所有以.py结尾的都可以认为是一个模块

 

 

例:编写一个.py结尾的文件实现四则运算,再用另一个.py文件去导入

 

 

 

###cacl.py文件,实现四则运算###

#!/usr/bin/env python

#coding:utf-8

from __future__ import division###__future__该模块中含有python3.x的方法,导入就可以使用这些方法###

def add(x,y):

    return x + y

def sub(x,y):

    return x -y

def multi(x,y):

    return x*y

def divi(x,y):

    return x/y

 

 

###hello.py文件,导入cacl.py文件###

#!/usr/bin/env python

#coding:utf-8

import cacl

print cacl.add(2,5)

print cacl.divi(5,2)

 

执行结果:

7

2.5

 

 

 

####导入模块的三种方法###

 

1 import cacl###导入cacl模块,使用时一定要加上cacl

 

例:

import cacl

print cacl.add(2,5)

print cacl.divi(5,2)

 

2 from   cacl   import add###导入cacl模块中的add方法,使用时不用加cacl,可以直接使用###

 

例:

from   cacl   import add

print add(2,5)

 

 

3 from cacl import add    as myadd###如果当前py代码包含add方法,但仍然想要使用cacl中的add方法,只需将cacl中的add方法重命名即可###

 

例:

from cacl import add    as myadd

 

def add(x,y):

    return  x+y+1

print add(2,5)

print myadd(2,5)

 

执行结果:

 

8

7

 

###导入模块的灵活应用####

 

1 导入模块的多个方法

from cacl import sub,multi###导入加法,减法###

from cacl import add    as myadd

 

def add(x,y):

    return  x+y+1

print add(2,5)

print sub(2,5)

print multi(2,5)

print myadd(2,5)

 

 

####路径搜索,搜索路径###

添加一路径,让路径搜索时导入相应的自定义模块

路径搜索:重点是在搜索

搜索路径:重点是在路径,即sys.path显示出来的路径

 

搜索路径:当你写了一个.py文件,想要在任何时刻的的都可以导入该模块,则需将该.py文件加入搜索路径中

 

In [3]: sys.path

Out[3]:

['',

 '/usr/bin',

 '/usr/lib64/python27.zip',

 '/usr/lib64/python2.7',

 '/usr/lib64/python2.7/plat-linux2',

 '/usr/lib64/python2.7/lib-tk',

 '/usr/lib64/python2.7/lib-old',

 '/usr/lib64/python2.7/lib-dynload',

 '/usr/lib64/python2.7/site-packages',

 '/usr/lib64/python2.7/site-packages/gtk-2.0',

 '/usr/lib/python2.7/site-packages',

 '/usr/lib/python2.7/site-packages/IPython/extensions',

 '/home/kiosk/.ipython']

 

In [4]: sys.path.append('/home/kiosk/PycharmProjects/pythonbasic/day05/')

 

In [5]: sys.path

Out[5]:

['',

 '/usr/bin',

 '/usr/lib64/python27.zip',

 '/usr/lib64/python2.7',

 '/usr/lib64/python2.7/plat-linux2',

 '/usr/lib64/python2.7/lib-tk',

 '/usr/lib64/python2.7/lib-old',

 '/usr/lib64/python2.7/lib-dynload',

 '/usr/lib64/python2.7/site-packages',

 '/usr/lib64/python2.7/site-packages/gtk-2.0',

 '/usr/lib/python2.7/site-packages',

 '/usr/lib/python2.7/site-packages/IPython/extensions',

 '/home/kiosk/.ipython',

 '/home/kiosk/PycharmProjects/pythonbasic/day05/']

 

In [6]: import decorate###加入搜索路径后,则可以导入###

hello....

1.00119495392

hello1....

None

hello2....

2.00213503838

hello3....

 

 

In [7]: sys.path.pop()

Out[7]: '/home/kiosk/PycharmProjects/pythonbasic/day05/'###一旦弹出,搜索路径中没有该路径时,就无法导入###

 

In [9]: sys.path

Out[9]:

['',

 '/usr/bin',

 '/usr/lib64/python27.zip',

 '/usr/lib64/python2.7',

 '/usr/lib64/python2.7/plat-linux2',

 '/usr/lib64/python2.7/lib-tk',

 '/usr/lib64/python2.7/lib-old',

 '/usr/lib64/python2.7/lib-dynload',

 '/usr/lib64/python2.7/site-packages',

 '/usr/lib64/python2.7/site-packages/gtk-2.0',

 '/usr/lib/python2.7/site-packages',

 '/usr/lib/python2.7/site-packages/IPython/extensions',

 '/home/kiosk/.ipython']

 

In [10]: import decorate

---------------------------------------------------------------------------

ImportError                               Traceback (most recent call last)

<ipython-input-10-96bbe2666044> in <module>()

----> 1 import decorate

 

ImportError: No module named decorate

 

 

 

 

###在day05下有一个hello.py文件,day06下也有一个hello.py文件,则是读取第一次导入的内容####

In [11]: sys.path.append('/home/kiosk/PycharmProjects/pythonbasic/day05/')

 

 

In [14]: import hello

 

In [15]: hello.hello1()

hello1.....inday05###day05下hello.py文件的内容###

 

In [16]: sys.path.append('/home/kiosk/PycharmProjects/pythonbasic/day06/')###将day06也加入搜索路径###

 

In [17]: import hello

 

In [18]: hello.hello1()

hello1.....inday05###显示的仍是day05的内容####

 

In [19]: sys.path

Out[19]:

['',

 '/usr/bin',

 '/usr/lib64/python27.zip',

 '/usr/lib64/python2.7',

 '/usr/lib64/python2.7/plat-linux2',

 '/usr/lib64/python2.7/lib-tk',

 '/usr/lib64/python2.7/lib-old',

 '/usr/lib64/python2.7/lib-dynload',

 '/usr/lib64/python2.7/site-packages',

 '/usr/lib64/python2.7/site-packages/gtk-2.0',

 '/usr/lib/python2.7/site-packages',

 '/usr/lib/python2.7/site-packages/IPython/extensions',

 '/home/kiosk/.ipython',

 '/home/kiosk/PycharmProjects/pythonbasic/day05/',

 '/home/kiosk/PycharmProjects/pythonbasic/day06/']

 

In [20]: sys.path.pop()

Out[20]: '/home/kiosk/PycharmProjects/pythonbasic/day06/'

 

In [21]: sys.path.insert(0,'/home/kiosk/PycharmProjects/pythonbasic/day06/')###就算将day06加到最前面,读取的仍然是day05的内容###

 

In [22]: import hello

 

In [23]: hello.hello1()

hello1.....inday05

 

 

####在还没有导入模块时,导入相同名字的模块,则,哪个路径在前,就先读取哪个,之后就算更改路径,仍然读取最初的模块####

In [2]: sys.path

Out[2]:

['',

 '/usr/bin',

 '/usr/lib64/python27.zip',

 '/usr/lib64/python2.7',

 '/usr/lib64/python2.7/plat-linux2',

 '/usr/lib64/python2.7/lib-tk',

 '/usr/lib64/python2.7/lib-old',

 '/usr/lib64/python2.7/lib-dynload',

 '/usr/lib64/python2.7/site-packages',

 '/usr/lib64/python2.7/site-packages/gtk-2.0',

 '/usr/lib/python2.7/site-packages',

 '/usr/lib/python2.7/site-packages/IPython/extensions',

 '/home/kiosk/.ipython']

 

In [3]: sys.path.insert(0,'/home/kiosk/PycharmProjects/pythonbasic/day06/')

 

In [4]: sys.path.append('/home/kiosk/PycharmProjects/pythonbasic/day06/')

 

In [5]: sys.path

Out[5]:

['/home/kiosk/PycharmProjects/pythonbasic/day06/',

 '',

 '/usr/bin',

 '/usr/lib64/python27.zip',

 '/usr/lib64/python2.7',

 '/usr/lib64/python2.7/plat-linux2',

 '/usr/lib64/python2.7/lib-tk',

 '/usr/lib64/python2.7/lib-old',

 '/usr/lib64/python2.7/lib-dynload',

 '/usr/lib64/python2.7/site-packages',

 '/usr/lib64/python2.7/site-packages/gtk-2.0',

 '/usr/lib/python2.7/site-packages',

 '/usr/lib/python2.7/site-packages/IPython/extensions',

 '/home/kiosk/.ipython',

 '/home/kiosk/PycharmProjects/pythonbasic/day05/']

 

In [6]: import hello

 

In [7]: hello.hello1()###读取day06的模块的内容###

hello1......in day06

 

In [8]: sys.path.pop()###弹出day05###

Out[8]: '/home/kiosk/PycharmProjects/pythonbasic/day05/'

 

In [9]: sys.path.insert(0,'/home/kiosk/PycharmProjects/pythonbasic/day05/')###将day05的路径加到最前面###

 

In [10]: sys.path

Out[10]:

['/home/kiosk/PycharmProjects/pythonbasic/day05/',

 '/home/kiosk/PycharmProjects/pythonbasic/day06/',

 '',

 '/usr/bin',

 '/usr/lib64/python27.zip',

 '/usr/lib64/python2.7',

 '/usr/lib64/python2.7/plat-linux2',

 '/usr/lib64/python2.7/lib-tk',

 '/usr/lib64/python2.7/lib-old',

 '/usr/lib64/python2.7/lib-dynload',

 '/usr/lib64/python2.7/site-packages',

 '/usr/lib64/python2.7/site-packages/gtk-2.0',

 '/usr/lib/python2.7/site-packages',

 '/usr/lib/python2.7/site-packages/IPython/extensions',

 '/home/kiosk/.ipython']

 

In [11]: import hello###导入hello模块###

 

In [12]: hello.hello1()###读取的仍然是day06下的内容###

hello1......in day06

 

 

 

 

 

 

####创建包###

 

import test.cacl    as cacl

def add(x,y):

    return  x+y+1

print add(2,5)

print cacl.sub(2,5)

 

 

 

####若是只导入test包,则需要在__init__.py文件里导入模块###

保存包的一些信息,其实是在解释执行test包里面的__init__.py文件

 

 

 

 

 

 

###类class###

 

编程:

面向过程

面向对象

面向函数

 

 

class Animals(object)###定义一个类,关键字class,类的名称的第一个字母一定要大写###

 

#!/usr/bin/env python

#coding:utf-8

class Animals(object):###定义类###

    cn = 'china'           ###类变量###

    def __init__(self,name,age):###构造函数,后面跟你要传递的参数

        self.name = name###self就是实例化的变量名,此时,self指的是haha,self.name是实例化属性,静态属性

        self.age = age

    def eating(self):###方法,与函数唯一的区别时self,动态属性###

        print "%s is eating..."%self.name

 

    def drink(self):

        print "%s is drinking..."%self.name

haha = Animals("fentiao",5)###实例化###

haha.eating()

haha.drink()

 

 

执行结果:

/usr/bin/python2.7 /home/kiosk/PycharmProjects/pythonbasic/day06/test/myclass.py

fentiao is eating...

fentiao is drinking...

 

Process finished with exit code 0

 

定义一个类变量和在构造函数__init__()内写入参数的区别,每次实例化的时候,都会执行构造函数,因此,若是执行次数很多的时候,构造函数里的参数就也执行很多次,因此,定义一个类变量会更方便

 

 

若是想要传递的参数不想要改变,可以加双下划线

 

###可以改变###

class Animals(object):

    cn = 'china'            ###类变量###

    def __init__(self,name,age,gender):

        self.name = name

        self.age = age

        self.gender = gender

    def eating(self):

        print "%s is eating..."%self.name

 

    def drink(self):

        print "%s is drinking..."%self.name

fentiao = Animals("fentiao",5,'male')

fentiao.eating()

fentiao.drink()

print fentiao.gender,fentiao.name

fentiao.gender = "female"

print fentiao.gender

 

 

###不可以改变###

class Animals(object):

    cn = 'china'            ###类变量###

    def __init__(self,name,age,gender):

        self.name = name

        self.age = age

        self.__gender = gender###以双下划线开头的变量是私有变量,在类外不可以访问,因为python编译器会将双下划线开头的变量进行更改,因此要打印双下划线开头的变量会报错(因为已经发生了改变,找不到)###

    def eating(self):

        print "%s is eating..."%self.name

 

    def drink(self):

        print "%s is drinking..."%self.name

fentiao = Animals("fentiao",5,'male')

fentiao.eating()

fentiao.drink()

print fentiao.__gender###打印不出,会报错###

 

 

想要打印,在类里再添加一个打印私有变量的方法:

 

class Animals(object):

    cn = 'china'            ###类变量###

    def __init__(self,name,age,gender):

        self.name = name

        self.age = age

        self.__gender = gender

    def eating(self):

        print "%s is eating..."%self.name

 

    def drink(self):

        print "%s is drinking..."%self.name

    def got_gender(self):

        return self.__gender

fentiao = Animals("fentiao",5,'male')

fentiao.eating()

fentiao.drink()

fentiao.__gender = "female"

print fentiao.__gender

print fentiao.got_gender()

 

执行结果:

/usr/bin/python2.7 /home/kiosk/PycharmProjects/pythonbasic/day06/test/myclass.py

fentiao is eating...

fentiao is drinking...

female

male###会发现没有改变###

 

Process finished with exit code 0

 

 

 

 

###私有方法###

class Animals(object):

    cn = 'china'            ###类变量###

    def __init__(self,name,age,gender):

        self.name = name

        self.age = age

        self.__gender = gender

    def eating(self):

        print "%s is eating..."%self.name

 

    def drink(self):

        print "%s is drinking..."%self.name

    def got_gender(self):

        self.__hello()

        return self.__gender

    def __hello(self):###定义私有方法###

        print "hello..."

fentiao = Animals("fentiao",5,'male')

print fentiao.got_gender()

print fentiao.__hello()###无法调用,会报错###

执行结果:

/usr/bin/python2.7 /home/kiosk/PycharmProjects/pythonbasic/day06/test/myclass.py

hello...

male

Traceback (most recent call last):

  File "/home/kiosk/PycharmProjects/pythonbasic/day06/test/myclass.py", line 84, in <module>

    print fentiao.__hello()

AttributeError: 'Animals' object has no attribute '__hello'

Process finished with exit code 0

 

###若是有不想被人访问的方法,则可以把它定义成私有方法###

 

 

 

 

面向对象的特性:

 

1 封装性:私有方法和私有属性

2 继承:继承父类的方法和属性

3 多态

 

 

 

 

###多态###

class Animals(object):###定义类###

    def __init__(self,name,age):###构造函数,后面跟你要传递的参数

        self.name = name###self就是实例化的变量名,此时,self指的是haha,self.name是实例化属性,静态属性

        self.age = age

    def eating(self):###方法,与函数唯一的区别时self,动态属性###

        print "%s is eating..."%self.name

 

    def drink(self):

        print "%s is drinking..."%self.name

haha = Animals("fentiao",5)###实例化###

haha.eating()

haha.drink()

 

class Cat(Animals):

    def eating(self):

        print '%s eating fish...'%(self.name)

class Dog(Animals):

    def eating(self):

        print "%s eating gutou......"%(self.name)

a1 = Animals('animals1',2)

a1.eating()

 

c1 = Cat('cat1',5)

c1.eating()

d1 = Dog('dog1',4)

d1.eating()

 

执行结果:

/usr/bin/python2.7 /home/kiosk/PycharmProjects/pythonbasic/day06/test/myclass.py

fentiao is eating...

fentiao is drinking...

animals1 is eating...

cat1 eating fish...

dog1 eating gutou......

 

 

 

 

 

 

 

 

###析构函数###

 

class Animals(object):###定义类###

    def __init__(self,name,age):###构造函数,后面跟你要传递的参数

        self.name = name###self就是实例化的变量名,此时,self指的是haha,self.name是实例化属性,静态属性

        self.age = age

    def eating(self):###方法,与函数唯一的区别时self,动态属性###

        print "%s is eating..."%self.name

 

    def drink(self):

        print "%s is drinking..."%self.name

    def __del__(self):

        print "that's all,game over"

haha = Animals("fentiao",5)###实例化###

haha.eating()

haha.drink()

 

class Cat(Animals):

    def eating(self):

        print '%s eating fish...'%(self.name)

class Dog(Animals):

    def eating(self):

        print "%s eating gutou......"%(self.name)

a1 = Animals('animals1',2)

a1.eating()

 

c1 = Cat('cat1',5)

c1.eating()

d1 = Dog('dog1',4)

d1.eating()

 

执行结果:

 

/usr/bin/python2.7 /home/kiosk/PycharmProjects/pythonbasic/day06/test/myclass.py

fentiao is eating...

fentiao is drinking...

animals1 is eating...

cat1 eating fish...

dog1 eating gutou......

that's all,game over

that's all,game over

that's all,game over

that's all,game over

 

Process finished with exit code 0

 

###或者####

class Animals(object):###定义类###

    def __init__(self,name,age):###构造函数,后面跟你要传递的参数

        self.name = name###self就是实例化的变量名,此时,self指的是haha,self.name是实例化属性,静态属性

        self.age = age

    def eating(self):###方法,与函数唯一的区别时self,动态属性###

        print "%s is eating..."%self.name

 

    def drink(self):

        print "%s is drinking..."%self.name

    def __del__(self):

        print "that's all,game over"

haha = Animals("fentiao",5)###实例化###

haha.eating()

haha.drink()

 

class Cat(Animals):

    def eating(self):

        print '%s eating fish...'%(self.name)

class Dog(Animals):

    def eating(self):

        print "%s eating gutou......"%(self.name)

a1 = Animals('animals1',2)

a1.eating()

del(a1)

 

c1 = Cat('cat1',5)

c1.eating()

del(c1)

d1 = Dog('dog1',4)

d1.eating()

del(d1)

 

执行结果:

/usr/bin/python2.7 /home/kiosk/PycharmProjects/pythonbasic/day06/test/myclass.py

fentiao is eating...

fentiao is drinking...

animals1 is eating...

that's all,game over

cat1 eating fish...

that's all,game over

dog1 eating gutou......

that's all,game over

that's all,game over

 

Process finished with exit code 0

 

 

 

######Animals.__init__(self,name,age)####

class Animals(object):###定义类###

    def __init__(self,name,age):###构造函数,后面跟你要传递的参数

        self.name = name###self就是实例化的变量名,此时,self指的是haha,self.name是实例化属性,静态属性

        self.age = age

    def eating(self):###方法,与函数唯一的区别时self,动态属性###

        print "%s is eating..."%self.name

 

    def drink(self):

        print "%s is drinking..."%self.name

    def __del__(self):

        print "that's all,game over"

haha = Animals("fentiao",5)###实例化###

haha.eating()

haha.drink()

 

class Cat(Animals):

    def __init__(self,name,age,color):

        Animals.__init__(self,name,age)

        self.color = color

    def eating(self):

        print '%s eating fish...'%(self.name)

    def info(self):

        print '''

                cat info

    name:%s

    age:%d

    color:%s

        '''%(self.name,self.age,self.color)

 

 

c1 = Cat('cat1',5,'black')

c1.info()

 

 

 

执行结果:

/usr/bin/python2.7 /home/kiosk/PycharmProjects/pythonbasic/day06/test/myclass.py

fentiao is eating...

fentiao is drinking...

 

                cat info

    name:cat1

    age:5

    color:black

        

that's all,game over

that's all,game over

 

Process finished with exit code 0

 

 

 

 

#####super(Cat,self).__init__(name,age)####

class Animals(object):###定义类###

    def __init__(self,name,age):###构造函数,后面跟你要传递的参数

        self.name = name###self就是实例化的变量名,此时,self指的是haha,self.name是实例化属性,静态属性

        self.age = age

    def eating(self):###方法,与函数唯一的区别时self,动态属性###

        print "%s is eating..."%self.name

 

    def drink(self):

        print "%s is drinking..."%self.name

    def __del__(self):

        print "that's all,game over"

haha = Animals("fentiao",5)###实例化###

haha.eating()

haha.drink()

class Cat(Animals):

    def __init__(self,name,age,color):

        # Animals.__init__(self,name,age)

        super(Cat,self).__init__(name,age)

        self.color = color

    def eating(self):

        print '%s eating fish...'%(self.name)

    def info(self):

        print '''

                cat info

    name:%s

    age:%d

    color:%s

        '''%(self.name,self.age,self.color)

 

 

c1 = Cat('cat1',5,'black')

c1.info()

 

执行结果:

/usr/bin/python2.7 /home/kiosk/PycharmProjects/pythonbasic/day06/test/myclass.py

fentiao is eating...

fentiao is drinking...

 

                cat info

    name:cat1

    age:5

    color:black

        

that's all,game over

that's all,game over

 

Process finished with exit code 0

 

 

 

####两个类之间建立联系,继承多个类####

 

 

class Realtion(object):

    def make_firends(self,obj):

        print "%s is %s friends"%(self.name,obj.name)

 

 

class Animals(object):###定义类###

    def __init__(self,name,age):###构造函数,后面跟你要传递的参数

        self.name = name###self就是实例化的变量名,此时,self指的是haha,self.name是实例化属性,静态属性

        self.age = age

    def eating(self):###方法,与函数唯一的区别时self,动态属性###

        print "%s is eating..."%self.name

 

    def drink(self):

        print "%s is drinking..."%self.name

    def __del__(self):

        print "that's all,game over"

haha = Animals("fentiao",5)###实例化###

haha.eating()

haha.drink()

 

 

 

 

 

class Cat(Animals,Realtion):

    def __init__(self,name,age,color):

        # Animals.__init__(self,name,age)

        super(Cat,self).__init__(name,age)

        self.color = color

    def eating(self):

        print '%s eating fish...'%(self.name)

    def info(self):

        print '''

                cat info

    name:%s

    age:%d

    color:%s

        '''%(self.name,self.age,self.color)

 

 

 

 

class Dog(Animals,Realtion):

     def eating(self):

         print "%s eating gutou......"%(self.name)

 

c1 = Cat('cat1',5,'black')

d1 = Dog("dog1",5)

c1.make_firends(d1)

 

 

 

执行结果:

/usr/bin/python2.7 /home/kiosk/PycharmProjects/pythonbasic/day06/test/myclass.py

fentiao is eating...

fentiao is drinking...

cat1 is dog1 friends

that's all,game over

that's all,game over

that's all,game over

 

Process finished with exit code 0

 

 

 

 

####继承策略###

广度优先策略(效率高)python3

深度优先策略:一直找父类的方法,如果没有找到相应的方法,再去找和c在同一层的类

 

 












本文转自blueclo51CTO博客,原文链接: http://blog.51cto.com/12774272/1947897,如需转载请自行联系原作者



版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。

相关文章
Python基础之:Python中的IO
IO就是输入和输出,任何一个程序如果和外部希望有交互的话,都需要使用到IO。相对于java而言,Python中的IO更加的简单,易用。 本文将会详细介绍Python中的IO操作。
168 0
Python基础
  Python基础                         作者:李斌 归档:学习笔记 2018/3/27       格式说明: 蓝色字体:注释 ...
954 0
阿里云服务器端口号设置
阿里云服务器初级使用者可能面临的问题之一. 使用tomcat或者其他服务器软件设置端口号后,比如 一些不是默认的, mysql的 3306, mssql的1433,有时候打不开网页, 原因是没有在ecs安全组去设置这个端口号. 解决: 点击ecs下网络和安全下的安全组 在弹出的安全组中,如果没有就新建安全组,然后点击配置规则 最后如上图点击添加...或快速创建.   have fun!  将编程看作是一门艺术,而不单单是个技术。
10668 0
Python基础框架和工具
最近在学Python金融大数据分析,在安装Python进行大数据分析的环境时遇到很多问题,例如:在安装pandas包时候就要到各种错误,总是缺少很多安装包,最后发现利用Python的Anaconda进行科学计算环境的搭建非常方便。
4011 0
Python基础知识(1)
Python 3 1:print:输出信息    例子:   ( 所有的标点符号都要是英文状态下输入,要不然会报错) print(“hello world”) 2:注意 : python 和 python3 3:ipython :在python前加i,此命令拥有和python类似的功能,但同时拥...
974 0
+关注
10146
文章
0
问答
文章排行榜
最热
最新
相关电子书
更多
《2021云上架构与运维峰会演讲合集》
立即下载
《零基础CSS入门教程》
立即下载
《零基础HTML入门教程》
立即下载