python—函数实例三

1.查询模块:按目录依次查找需要导入的模块,模块目录一般在:/usr/lib64/python2.7

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
In [ 2 ]: sys.path
Out[ 2 ]:
['',
'/usr/bin' ,
'/usr/lib64/python2.7/site-packages/MySQL_python-1.2.5-py2.7-linux-x86_64.egg' ,
'/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/lib/python2.7/site-packages' ,
'/usr/lib/python2.7/site-packages/python_memcached-1.58-py2.7.egg' ,
'/usr/lib/python2.7/site-packages/IPython/extensions' ,
'/root/.ipython' ]


2.自定义模块目录

方法一:sys.path.append(),一般加在目录列表最后

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
In [ 3 ]: sys.path.append( "/root/python/" )
In [ 4 ]: sys.path
Out[ 4 ]:
['',
'/usr/bin' ,
'/usr/lib64/python2.7/site-packages/MySQL_python-1.2.5-py2.7-linux-x86_64.egg' ,
'/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/lib/python2.7/site-packages' ,
'/usr/lib/python2.7/site-packages/python_memcached-1.58-py2.7.egg' ,
'/usr/lib/python2.7/site-packages/IPython/extensions' ,
'/root/.ipython' ,
  '/root/python/' ]


方法二:修改环境变量,一般加在目录列表前面

1
2
vim  /root/ .bashrc    # 加入 export PYTHONPATH=/root/python
source  /root/ .bashrc   # 刷新


例子:统计一个文件,行数、单词数、字符数(和wc命令相同效果)

说明:为了避免使用split切割之后,最后多出一个空字符串,而使用count()

1
2
3
4
5
6
7
8
9
10
#/usr/bin/env python
def  count(s):
     char  =  len (s)
     words  =  len (s.split())
     lines  =  s.count( "\n" )
     print  lines,words,char
 
file1  =  open ( "/etc/passwd" , "r" )
=  file1.read()
count(s)


3.脚本形式,导入模块,脚本名字不能是数字,会产生一个编译文件

例子:

1
2
#!/usr/bin/env python
import  wc

说明:目录下生产编译文件:wc.pyc



4.py和wc.py的__name__内置变量不一样,前者是wc,或者是__main__,修改wc.py,执行自己时,输出自己的结果,被调用时,执行不显示源结果:

wc.py:

1
2
3
4
5
6
7
8
9
10
11
#/usr/bin/env python
def  count(s):
     char  =  len (s)
     words  =  len (s.split())
     lines  =  s.count( "\n" )
     print  lines,words,char
 
if  __name__  = =  "__main__"
     file1  =  open ( "/etc/passwd" , "r" )
     =  file1.read()
     count(s)

test.py:

1
2
3
4
#!/usr/bin/env python
import  wc
=  open ( "/root/python/10.py" , "r" ).read()
wc.count(s)

5.包的形式,导入模块

四种导入方法:在包目录dir下创建一个__init__.py空文件

方法一:

1
2
from  dir  import  wc
wc.count( "abc" )


方法二:

1
2
import  dir .wc
dir .wc.count( "abc" )


方法三:

1
2
from  dir .wc  import  count
count( "abc" )


方法四:别名

1
2
from  dir .wc  import  count as count
count( "abc" )


6.面向对象编程:python、java、C++;面向过程编程:C、函数式编程、shell

类的(静态)属性:(人类的五官,理解为变量)

类的(动态)方法:(人类吃穿住行,理解为一个函数)

对象:类的实例化,之后才能有属性和方法



7.类的创建

类的方法中,至少有一个参数self

调用属性时,不带括号

调用方法时,使用括号;方法调用属性时,至少有一个self参数

属性调用其他方法:类名.属性名


例子:

1
2
3
4
5
6
7
8
9
class  People():
     color  =  "yellow"
     def  think( self ):                 # 加上self表示是类的方法,不加则表示函数
         self .color  =  "black"     # 加上self表示是类的属性
         print  ( "My color is %s " %  ( self .color))
 
ren  =  People()          # 类的实例化
print  ren.color           # 类的属性外部调用
ren.think()                # 类的方法外部调用,如加上print,则多一个默认return值none

运行结果:

yellow

My color is black



8.私有属性在定义的类中的内部函数中被调用

例子:

1
2
3
4
5
6
7
8
9
10
class  People():
     color  =  "yellow"
     __age  =  27
     def  think( self ):
         self .color  =  "black"
         print  self .__age                          # 内部函数调用类的私有属性,外部函数不能直接调用
         print  ( "My color is %s " %  ( self .color))
ren  =  People()
print  ren.color
ren.think()


9.外部调用私有属性(格式:实例化名._类名属性名),一般只是测试用

例子:

1
2
3
4
5
6
7
8
9
10
11
12
class  People():
     color  =  "yellow"
     __age  =  27
     def  think( self ):
         self .color  =  "black"
         print  self .__age
         print  ( "My color is %s " %  ( self .color))
 
ren  =  People()
print  ren.color
ren.think()
print  ren._People__age           # 外部调用私有属性


10.类的方法

公有方法:内部和外部都可以调用

私有方法:内部函数调用

动态方法:classmethod()函数处理,没有被调用的类的其他参数不会加载进内存中

静态方法:


方法的定义和函数一样,但是需要把self作为第一个参数,如果还是有其他参数,继续加上;类实例化之后,采用“类名.方法名()”调用


例子1:私有方法调用

1
2
3
4
5
6
7
8
9
10
11
class  People():
     color  =  "yellow"
     __age  =  27
     def  __think( self ):
         self .color  =  "black"
         print  self .__age
         print  ( "My color is %s " %  ( self .color))
     def  test( self ):
         self .__think()            # 类的私有方法调用
ren  =  People()
ren.test()                         # 类的私有方法调用


例子2:动态方法调用

1
2
3
4
5
6
7
8
9
10
11
12
13
class  People():
     color  =  "yellow"
     __age  =  27
     def  __think( self ):
         self .color  =  "black"
         print  self .__age
         print  ( "My color is %s " %  ( self .color))
     def  test( self ):
         print  ( "Testing..."
     cm  =  classmethod (test)         # 动态方法定义
 
ren  =  People()
ren.cm()                                    # 动态方法调用


例子3:静态方法调用:

类函数不带self参数,该函数使用staticmethod()函数处理(如果不处理,缺少self,,调用时会报错),加载关于这个类的所有东西

1
2
3
4
5
6
7
8
9
10
11
12
13
class  People():
     color  =  "yellow"
     __age  =  27
     def  __think( self ):
         self .color  =  "black"
         print  self .__age
         print  ( "My color is %s " %  ( self .color))
     def  test():                                  #  内部函数,不带self
         print  ( "Testing..."
        #print People.color              # 因为没有self,不能调用该类的属性    
     cm  =  staticmethod (test)           # 静态方法定义
ren  =  People()
ren.cm()                                      # 静态方法调用


例子4:加装饰器,只对下面的一个函数起作用,就可以使用类的方法调用了

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class  People():
     color  =  "yellow"
     __age  =  27
     def  __think( self ):
         self .color  =  "black"
         print  self .__age
         print  ( "My color is %s " %  ( self .color))
     
     @ classmethod                  # 加装饰器,可以通过类来调用
     def  test( self ):                    # 动态方法,带self
         print  ( "Testing..." )
     
     @ staticmethod                # 加装饰器
     def  test1():                      # 静态方法,不带self
         print  ( "Testing1.." )
 
ren  =  People()
People.test()                  # 类的方法调用
People.test1()                # 类的方法调用



11.定义内部类

方法一:

1
2
3
4
5
6
7
class  People():
     color  =  "yellow"
     __age  =  27
     class  Chinese( object ):      # 定义内部类
         country  =  "I am chinese"
hzp  =  People.Chinese()       # 外部类.内部类实例化
print  hzp.country                 # 实例化后,调用内部类的属性


方法二:

1
2
3
4
5
6
7
8
class  People():
     color  =  "yellow"
     __age  =  27
     class  Chinese( object ):
         country  =  "I am chinese"
hzp  =  People()                   # 先外部类实例化
hzp2  =  hzp.Chinese()        # 再内部类实例化
print  hzp2.country


方法三:

1
2
3
4
5
6
7
class  People():
     color  =  "yellow"
     __age  =  27
     class  Chinese( object ):
         country  =  "I am chinese"
print  People.Chinese.country                 # 类的方法
print  People.Chinese().country              # 相当于People.Chinese()实例化,最后调用属性



12.构造函数和析构函数

构造函数用于初始化类的内部状态,提供的函数是__init__(),不给出则会提供默认方法

析构函数用于释放占用的资源,提供的函数是__del__(),不给出则会提供默认方法


1)__str__(self):只能使用return,不能使用print,无需调用和打印,会自动调用

例子1:

1
2
3
4
5
6
7
8
9
10
class  People():
     color  =  "yellow"
     __age  =  27
     class  Chinese( object ):
         country  =  "I am chinese"
     def  __str__( self ):                 # 定义__str__(self)
         return ( "This is a test" )     # return返回结果,不能使用print
 
ren  =  People()
print  ren                                 # 类实例化后,自动调用


运行结果:

This is a test


2)__init__():初始化值,不需调用,实例化后,自动执行,也可以传值

例子2:

1
2
3
4
5
6
7
8
9
10
11
12
13
class  People():
     color  =  "yellow"
     __age  =  27
     class  Chinese( object ):
         country  =  "I am chinese"
     def  __str__( self ):
         return ( "This is a test" )
     def  __init__( self ):
         self .color  =  "black"
 
ren  =  People()
print  ren.color            # 实例化后,变成“black”
print  People.color      # 类直接调用,color值不变


运行结果:

black

yellow



3)__del__():在脚本最后执行,释放资源;如果没有析构函数释放资源,也没关系,python通过gc模块,实现垃圾回收机制

例子3:


1
2
3
4
5
6
7
8
9
class  People():
     def  __init__( self ):          # 构造函数,打开文件
         print ( "Initing..." )
         self .fd  =  open ( "/etc/hosts" , "r" ):
     def  __del__( self ):        # 析构函数,关掉文件
         print ( "End" )
         self .fd.close()
ren  =  People()
ren

运行结果:

Initing...

End










本文转自 huangzp168 51CTO博客,原文链接:http://blog.51cto.com/huangzp/2047412,如需转载请自行联系原作者
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值