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,如需转载请自行联系原作者
目录
相关文章
|
21小时前
|
测试技术 开发者 Python
Python检查函数和方法的输入/输出
【5月更文挑战第5天】Python检查函数和方法的输入/输出
9 1
|
1天前
|
Python
在Python中,利用`os模块`的`path.exists()`函数可判断文件是否存
在Python中,利用`os模块`的`path.exists()`函数可判断文件是否存在,该函数对路径进行检查,存在则返回True,不存在则返回False。示例代码展示了如何检查'example.txt'文件是否存在并相应打印消息。此外,`os.path.isfile()`用于确认路径是否为文件,仅当是文件时返回True,否则返回False,同样配以示例说明其用法。
8 2
|
2天前
|
Python
【Python操作基础】——函数
【Python操作基础】——函数
|
2天前
|
Python
Python的全局变量作用于整个程序,生命周期与程序相同,而局部变量仅限函数内部使用,随函数执行结束而销毁。
Python的全局变量作用于整个程序,生命周期与程序相同,而局部变量仅限函数内部使用,随函数执行结束而销毁。在函数内部修改全局变量需用`global`关键字声明,否则会创建新局部变量。
9 2
|
5天前
|
数据采集 NoSQL 中间件
python-scrapy框架(四)settings.py文件的用法详解实例
python-scrapy框架(四)settings.py文件的用法详解实例
9 0
|
5天前
|
Java C# 开发者
Python 中的类型注解是一种用于描述变量、函数参数和返回值预期类型的机制
Python的类型注解提升代码可读性和可维护性,虽非强制,但利于静态类型检查(如Mypy)。包括:变量注解、函数参数和返回值注解,使用内置或`typing`模块的复杂类型,自定义类型注解,以及泛型模拟。类型注解可在变量声明、函数定义和注释中使用,帮助避免类型错误,提高开发效率。
16 6
|
7天前
|
存储 Python
【Python 基础】解释reduce函数的工作原理
【5月更文挑战第6天】【Python 基础】解释reduce函数的工作原理
|
7天前
|
Python
【Python 基础】解释map函数的工作原理
【5月更文挑战第6天】【Python 基础】解释map函数的工作原理
|
7天前
|
索引 Python
【Python 基础】解释Range函数
【5月更文挑战第6天】【Python 基础】解释Range函数
|
7天前
|
数据可视化 Python
python中Copula在多元联合分布建模可视化2实例合集|附数据代码
python中Copula在多元联合分布建模可视化2实例合集|附数据代码