Python学习 【三】:函数基础

一、三元运算符

  三运运算又称三目运算,和其他语言有些区别。其实就是一种简写的if-else语句

1 #格式
2 
3 result = 值1 if 条件 else 值2
4 
5 #如果条件成立,将值1赋值给result否则将值2赋值给result

 

二、深浅拷贝

 1、数字与字符串

    对于 数字字符串 来说,赋值、深浅拷贝都是没有意义的,因为所有变量都指向一个内存空间

 1 import copy
 2 
 3 #数字与字符串的测试
 4 
 5 num1 = 2555
 6 #打印num1在内存中的位置
 7 print(id(num1))
 8 
 9 #赋值
10 num2 = num1
11 print(id(num2))
12 
13 #浅拷贝
14 num2 = copy.copy(num1)
15 print(id(num2))
16 
17 #深拷贝
18 num3 = copy.deepcopy(num1)
19 print(id(num3))
20 
21 
22 #经过测试会发现,num2的内存地址永远与num1一直,字符串同理操作

    在内存中的情况如下图:无论怎么拷贝都是指向同一个地址

 2、其它类型的拷贝

    对应列表,元组,字典这些可迭代类型的变量拷贝时,情况是不一样的。

    1.赋值

       赋值只是简单的将一个对象的引用给另外一个对象,使得两个对象同时指向一块内存地址

1 obj1 = {'k1':'zss','k2':123,'k3':[234,'cmd']}
2 
3 obj2 = obj1

      如下图所示:

    2.浅拷贝

      在内存中额外新建第一层,不进行内部拷贝,采用copy库中coyp.copy函数进行浅拷贝,内存情况如下:

 

    3.深拷贝

       深拷贝在内存中对该对象所有的数据重新进行创建,但是Python内部优化,即数字和字符串不重新创建,内存中情况如下:

 

这就是Python中的深浅拷贝,在平时使用的时候可以使用copy中copy.copy函数进行浅拷贝,使用copy.deepcopy函数进行深拷贝。哦!对了什么是函数呢?让我们继续来学习!

三、函数基础

1.含义

  这里指的函数不同于数学上的函数定义,我在这里将函数理解为可以接受参数的,返回参数的,完成某一或某些功能的代码的集合。

  为什么要使用函数呢?我认为可以减少重复编码的时间,同一功能的代码可以不用重复编码多次。增强代码的可读性和重用性

  让我们看看在python中如何使用函数

2.定义及使用

1 def 函数名(参数):#函数名不可为中文
2     ...
3     函数体
4     ...
5     return 返回值 #python中如果没有写return语句,默认返回null

  函数的定义需要注意以下:

  • def:表示函数的关键字
  • 函数名:函数的名称,日后根据函数名调用函数
  • 函数体:函数中进行一系列的逻辑计算,如:发送邮件、计算出 [11,22,38,888,2]中的最大数等...
  • 参数:为函数体提供数据
  • 返回值:当函数执行完毕后,可以给调用者返回数据。

  1.返回值

  函数是一个功能块,该功能到底执行成功与否,需要通过返回值来告知调用者。通过使用return关键字来实现。

  2.参数

  参数和返回值在函数中是比较重要的两个概念。参数可以在函数代码体运行的过程中,每次调用可以使用不同的数据进行代码运行,从而方便调用者使用。

  Python中参数分三种:普通参数,默认参数,动态参数。

 1 #参数可以为任意类型,使用时实参必须和调用函数定义的形式参数类型顺序一直
 2 def fun1(name,pwd)
 3     函数体
 4 
 5 
 6 #调用时,采用函数名加实参
 7 fun1('zss',123)
 8 #此时zss对应name参数,123对应pwd参数
 9 #如果想改变顺序可以使用如下方法
10 fun1(pwd=123,name='zss')
普通参数
1 def fun(pwd,name = 'zss')
2 #注意,含有默认值的形参必须放在最后 不然语法错误报错
3     函数体
4 
5 
6 fun(123,cmd)
7 #下面一种也能调用
8 fun(123)
默认参数
 1 def fun(*args)
 2 #此时,python中将args作为元组类型处理,可接受无限多元素
 3     print(args)
 4 
 5 
 6 #调用方法1
 7 def(1,2,3,4,5)
 8 
 9 #调用方法2
10 list = [1,2,3,4,5]
11 def(*list)
12 #list 可以是元组或列表
动态参数1
 1 def fun(**kvargs):
 2 #将多个参数转换为字典类型,kvargs为字典类型
 3     print(kvargs)
 4 
 5 
 6 #调用方法1
 7 fun(name='zss',pwd=123)
 8 
 9 #调用方法2
10 dict = {'name':'zss','pwd':123}
11 fun(**dict)
动态参数2

  可以将两种动态参数组合使用,一般使用形参args 和 kwargs。当两个同时使用的时候,*args必须在**kwargs之前

四、函数装饰器

    我们已经初步了解了Python中的函数的一些基本知识。了解到创建函数的时候必须要有函数名

  那有没有考虑过一个问题,如果两个函数名一样的函数,那执行的时候究竟会先执行哪一个?

 1 def fun():
 2     print('这是函数1')
 3 
 4 def fun():
 5     print('这是函数2')
 6 
 7 fun()
 8 #那在执行的时候究竟会执行哪一个呢?
 9 #经过执行可以发现,会打印 ‘ 这是函数2’
10 
11 #函数和变量一样,在解释器解释之后会存放在内存中,用函数名引用
12 #当重新写一个函数名一样的函数时,相同的函数名会指向一个新的地址,新的函数
13 #所以函数被改变了

    那么这和Python中的装饰器有什么关系呢?当有这样一个场景,如果我有100个函数,我都要在函数执行之前增加一些代码。

  如果要符合代码的开放封闭原则,我们就会采用装饰器来装饰我们的函数。

#这是装饰器函数
def outer(func):
    def inner():
        print('增加新功能')
        re = func()
        print('增加新功能2‘)return re
    return inner

#使用装饰器,使用@标签
@outer
def f1():
    print('原功能‘)return 'zss'

re = f1()

    当Python解释器执行到装饰器@的时候,会自动执行一下功能:

  • 执行@后面的函数,将下面的函数名f1作为参数,传递给装饰器函数执行
  • 将装饰器函数outer的返回值重新赋值给f1,所以f1函数名现在所指的是inner函数

    此时f1所指的inner函数执行过程中的func指向原来的f1函数,这样就使用inner将原来的函数进行装饰,但是还是通过f1调用函数。

   如果我函数参数很多,怎么办?

#这是装饰器函数
def outer(func):
    def inner(*args, **kwargs):
        print('增加新功能')
        re = func(*args, **kwargs)
        print('增加新功能2‘)return re
    return inner

#使用装饰器,使用@标签
@outer
def f1(s1, s2, s3):
    print('原功能‘)return 'zss'

@outer
def f2(s1, s2):
    print('原功能‘)return 'zss'

re = f1(1, 2, 3),
re2 = f2(1, 2)

#使用动态参数,Python内部自动分配参数给函数

  装饰器外部还可以再进行装饰吗? 那是肯定的

#这是装饰器函数1
def outer_1(func):
    def inner(*args, **kwargs):
        print('增加新功能1')
        re = func(*args, **kwargs)
        print('增加新功能2‘)return re
    return inner

#这是装饰器函数2
def outer_2(func):
    def inner(*args, **kwargs):
        print('增加新功能3')
        re = func(*args, **kwargs)
        print('增加新功能4‘)return re
    return inner


#使用装饰器,使用@标签
@outer_2
@outer_1
def f1(s1, s2, s3):
    print('原功能‘)return 'zss'

re = f1(1, 2, 3)

    这究竟如何运行呢? 其实很简单,看下面的图:

    这就是简单的Python装饰器

五、杂项二

1、内置函数

  

注:查看详细 猛戳这里

  1 #整理一下这些内置函数
  2 
  3 #对参数取绝对值
  4 abs() 
  5 
  6 #当所有参数为真的时候返回真
  7 all()
  8 
  9 #只要有一个参数为真返回真
 10 any()
 11 
 12 #这两个函数都是调用参数类内部的__repr__方法获得返回值
 13 ascii()
 14 repr()
 15 
 16 #二进制,八进制,十进制,十六进制
 17 bin()
 18 oct()
 19 int()
 20 hex()
 21 #实例,将二进制数转换为十进制,base表示进制,前一个参数表示进制数串
 22 re = int('0b11', base = 2)
 23 
 24 #字节函数,字节列表函数
 25 bytes()
 26 bytearray()
 27 #实例,将字符串转换为字节
 28 bytes(字符串,encoding='utf-8')
 29 #字符串和字节的相互转换
 30 s = 'zss'
 31 b = s.encode()#b就是字节
 32 s2 = b.decode()#s2是b转换后的字符串,
 33 #注此时s和s2虽然字符串一样,但是内存地址不一样
 34 
 35 #字符与对应的ascii码转换
 36 chr()#将输入的数字参数转换为对应的字符
 37 ord()#将输入的字符参数转换为对应的数字
 38 
 39 #判断是否可执行
 40 callable()
 41 
 42 #dir快速查看某一指令的帮助,help详细查看某一指令的帮助
 43 dir()
 44 help()
 45 
 46 #得到商和余数,得到一个元组
 47 #在做分页功能的时候使用
 48 divmod()
 49 #实例,结果为(3,1)
 50 t = divmod(10,3)
 51 print(t)
 52 
 53 #将字符串中的表达式计算出结果
 54 eval()
 55 #实例1,将字符串中的表达式计算出结果257
 56 sum = eval('123+234')
 57 #实例2,字符串中的表达式可以存在变量,通过字典类型给变量赋值
 58 sum = eval('a+123',{'a':234})
 59 
 60 #处理符合Python语法的字符串,执行字符串中的代码
 61 exec()
 62 
 63 #编译字符串中的代码
 64 complie()
 65 
 66 #过滤,得到结果为真的参数
 67 #循环可迭代对象,让每个元素作为函数参数运行函数
 68 #返回True的放到该方法生成的一个filter对象中
 69 filter(函数,可迭代对象)
 70 #实例
 71 def f1(x):
 72     if x>22:
 73         return True
 74     return False
 75 f = filter(f1,[11,22,33,44])
 76 #对于简单的函数,可以使用lambda表达式
 77 f2 = filter(lambda x:x>22,[11,22,33,44])
 78 
 79 #批量操作,可以将迭代对象一个一个作为参数运行函数,得到结果是map对象
 80 map(函数,可迭代对象)
 81 
 82 #字符串格式化函数
 83 format()
 84 
 85 #获取代码中的全局变量和局部变量
 86 globals()
 87 locals()
 88 
 89 #获取参数的哈希值
 90 hash()
 91 
 92 #判断参数是否是类的实例化
 93 isinstance(对象,类)
 94 #判断参数是否是后面一个参数的子类
 95 issubclass()
 96 
 97 #创建可被迭代的对象
 98 iter()
 99 #循环iter函数创建的可迭代对象,每次取一个数
100 next()
101 
102 #字符串翻转
103 reversed()
104 
105 #四舍五入
106 round()
107 
108 #排序
109 sorted()
110 
111 #将两个迭代对象合并成一个迭代对象
112 zip()
113 
114 #导入
115 __import__()
116      

 

2、lambda表达式

对于简单if-else我们可以使用三元运算来进行。

那么对于一些很简单的函数,我们可以使用简便方法吗?答案那是肯定的,我们可以使用lambda表达式,如下:

 1 #简单函数,正常定义
 2 def fun(arg):
 3     return(arg+1)
 4 
 5 #执行简单函数
 6 result = fun(123)
 7 
 8 #使用lambda表达式
 9 my_lambda = lambda arg:arg+1
10 #执行函数
11 result = my_lambda(123)

对于一些简单的函数,我们可以使用这种方法。

3、递归(函数可以调用本身)

利用函数编写如下数列:

斐波那契数列指的是这样一个数列 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233,377,610,987,1597,2584,4181,6765,10946,17711,28657,46368...

斐波那契数列是一个典型的使用递归就可以解决的数列。

1 def func(arg1,arg2):
2     if arg1 == 0:
3         print arg1, arg2
4     arg3 = arg1 + arg2
5     print arg3
6     func(arg2, arg3)
7   
8 func(0,1)

 

4、排序

  python中使用内置函数sorted函数,有以下两点需要注意:

  1. 只能有同一种类型进行排序
  2. 字符串进行比较的时候(数字-字母/符号-汉字)

    字符串比较的时候,字符串数字比较最前面一个数字或相同则比较后面一个,并不是按照该数字大小。

    字母/符号采用ascii码进行比较

    中文使用utf-8编码进行比较,先比较最前面一个,相同则比较后面。

 

5、文件操作

 文件操作通常包括下面三步:

  • 打开文件
  • 操作文件
  • 关闭文件
  (1)打开文件

    使用open函数进行打开文件操作。

f = open(文件名(路径),模式,编码)
#由f变量代指这个文件,可以进行操作

  打开文件的模式有:

  • r ,只读模式【默认】
  • w,只写模式【不可读;不存在则创建;存在则清空内容;】
  • x, 只写模式【不可读;不存在则创建,存在则报错】
  • a, 追加模式【不可读;   不存在则创建;存在则只追加内容;】

"+" 表示可以同时读写某个文件

  • r+, 读写【可读,可写】,文件指针指向开头,从开头写
  • w+,写读【可读,可写】,清空已存在文件的 内容,文件指针指向开头
  • x+ ,写读【可读,可写】
  • a+, 写读【可读,可写】,文件指针指向末尾,在末尾添加

 "b"表示以字节的方式操作,此方法无须进行编码

  • rb  或 r+b
  • wb 或 w+b
  • xb 或 w+b
  • ab 或 a+b

 注:以b方式打开时,读取到的内容是字节类型,写入时也需要提供字节类型

  文件打开的另一种形式:

1 with open('zss.txt','r',encoding='utf-8') as obj1, open(....) as obj2:
2     文件操作代码
3 
4 #自动执行f.close()
5 #python2.7以后支持同时打开两个文件
  (2)操作文件
class file(object)
    def close(self): # real signature unknown; restored from __doc__
        关闭文件
        """
        close() -> None or (perhaps) an integer.  Close the file.
         
        Sets data attribute .closed to True.  A closed file cannot be used for
        further I/O operations.  close() may be called more than once without
        error.  Some kinds of file objects (for example, opened by popen())
        may return an exit status upon closing.
        """
 
    def fileno(self): # real signature unknown; restored from __doc__
        文件描述符  
         """
        fileno() -> integer "file descriptor".
         
        This is needed for lower-level file interfaces, such os.read().
        """
        return 0    
 
    def flush(self): # real signature unknown; restored from __doc__
        刷新文件内部缓冲区
        """ flush() -> None.  Flush the internal I/O buffer. """
        pass
 
 
    def isatty(self): # real signature unknown; restored from __doc__
        判断文件是否是同意tty设备
        """ isatty() -> true or false.  True if the file is connected to a tty device. """
        return False
 
 
    def next(self): # real signature unknown; restored from __doc__
        获取下一行数据,不存在,则报错
        """ x.next() -> the next value, or raise StopIteration """
        pass
 
    def read(self, size=None): # real signature unknown; restored from __doc__
        读取指定字节数据
        """
        read([size]) -> read at most size bytes, returned as a string.
         
        If the size argument is negative or omitted, read until EOF is reached.
        Notice that when in non-blocking mode, less data than what was requested
        may be returned, even if no size parameter was given.
        """
        pass
 
    def readinto(self): # real signature unknown; restored from __doc__
        读取到缓冲区,不要用,将被遗弃
        """ readinto() -> Undocumented.  Don't use this; it may go away. """
        pass
 
    def readline(self, size=None): # real signature unknown; restored from __doc__
        仅读取一行数据
        """
        readline([size]) -> next line from the file, as a string.
         
        Retain newline.  A non-negative size argument limits the maximum
        number of bytes to return (an incomplete line may be returned then).
        Return an empty string at EOF.
        """
        pass
 
    def readlines(self, size=None): # real signature unknown; restored from __doc__
        读取所有数据,并根据换行保存值列表
        """
        readlines([size]) -> list of strings, each a line from the file.
         
        Call readline() repeatedly and return a list of the lines so read.
        The optional size argument, if given, is an approximate bound on the
        total number of bytes in the lines returned.
        """
        return []
 
    def seek(self, offset, whence=None): # real signature unknown; restored from __doc__
        指定文件中指针位置
        """
        seek(offset[, whence]) -> None.  Move to new file position.
         
        Argument offset is a byte count.  Optional argument whence defaults to
(offset from start of file, offset should be >= 0); other values are 1
        (move relative to current position, positive or negative), and 2 (move
        relative to end of file, usually negative, although many platforms allow
        seeking beyond the end of a file).  If the file is opened in text mode,
        only offsets returned by tell() are legal.  Use of other offsets causes
        undefined behavior.
        Note that not all file objects are seekable.
        """
        pass
 
    def tell(self): # real signature unknown; restored from __doc__
        获取当前指针位置
        """ tell() -> current file position, an integer (may be a long integer). """
        pass
 
    def truncate(self, size=None): # real signature unknown; restored from __doc__
        截断数据,仅保留指定之前数据
        """
        truncate([size]) -> None.  Truncate the file to at most size bytes.
         
        Size defaults to the current file position, as returned by tell().
        """
        pass
 
    def write(self, p_str): # real signature unknown; restored from __doc__
        写内容
        """
        write(str) -> None.  Write string str to file.
         
        Note that due to buffering, flush() or close() may be needed before
        the file on disk reflects the data written.
        """
        pass
 
    def writelines(self, sequence_of_strings): # real signature unknown; restored from __doc__
        将一个字符串列表写入文件
        """
        writelines(sequence_of_strings) -> None.  Write the strings to the file.
         
        Note that newlines are not added.  The sequence can be any iterable object
        producing strings. This is equivalent to calling write() for each string.
        """
        pass
 
    def xreadlines(self): # real signature unknown; restored from __doc__
        可用于逐行读取文件,非全部
        """
        xreadlines() -> returns self.
         
        For backward compatibility. File objects now include the performance
        optimizations previously implemented in the xreadlines module.
        """
        pass

2.x
Python2.X
class TextIOWrapper(_TextIOBase):
    """
    Character and line based layer over a BufferedIOBase object, buffer.
    
    encoding gives the name of the encoding that the stream will be
    decoded or encoded with. It defaults to locale.getpreferredencoding(False).
    
    errors determines the strictness of encoding and decoding (see
    help(codecs.Codec) or the documentation for codecs.register) and
    defaults to "strict".
    
    newline controls how line endings are handled. It can be None, '',
    '\n', '\r', and '\r\n'.  It works as follows:
    
    * On input, if newline is None, universal newlines mode is
      enabled. Lines in the input can end in '\n', '\r', or '\r\n', and
      these are translated into '\n' before being returned to the
      caller. If it is '', universal newline mode is enabled, but line
      endings are returned to the caller untranslated. If it has any of
      the other legal values, input lines are only terminated by the given
      string, and the line ending is returned to the caller untranslated.
    
    * On output, if newline is None, any '\n' characters written are
      translated to the system default line separator, os.linesep. If
      newline is '' or '\n', no translation takes place. If newline is any
      of the other legal values, any '\n' characters written are translated
      to the given string.
    
    If line_buffering is True, a call to flush is implied when a call to
    write contains a newline character.
    """
    def close(self, *args, **kwargs): # real signature unknown
        关闭文件
        pass

    def fileno(self, *args, **kwargs): # real signature unknown
        文件描述符  
        pass

    def flush(self, *args, **kwargs): # real signature unknown
        刷新文件内部缓冲区
        pass

    def isatty(self, *args, **kwargs): # real signature unknown
        判断文件是否是同意tty设备
        pass

    def read(self, *args, **kwargs): # real signature unknown
        读取指定字节数据
        pass

    def readable(self, *args, **kwargs): # real signature unknown
        是否可读
        pass

    def readline(self, *args, **kwargs): # real signature unknown
        仅读取一行数据
        pass

    def seek(self, *args, **kwargs): # real signature unknown
        指定文件中指针位置
        pass

    def seekable(self, *args, **kwargs): # real signature unknown
        指针是否可操作
        pass

    def tell(self, *args, **kwargs): # real signature unknown
        获取指针位置
        pass

    def truncate(self, *args, **kwargs): # real signature unknown
        截断数据,仅保留指定之前数据
        pass

    def writable(self, *args, **kwargs): # real signature unknown
        是否可写
        pass

    def write(self, *args, **kwargs): # real signature unknown
        写内容
        pass

    def __getstate__(self, *args, **kwargs): # real signature unknown
        pass

    def __init__(self, *args, **kwargs): # real signature unknown
        pass

    @staticmethod # known case of __new__
    def __new__(*args, **kwargs): # real signature unknown
        """ Create and return a new object.  See help(type) for accurate signature. """
        pass

    def __next__(self, *args, **kwargs): # real signature unknown
        """ Implement next(self). """
        pass

    def __repr__(self, *args, **kwargs): # real signature unknown
        """ Return repr(self). """
        pass

    buffer = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default

    closed = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default

    encoding = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default

    errors = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default

    line_buffering = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default

    name = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default

    newlines = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default

    _CHUNK_SIZE = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default

    _finalizing = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default

3.x
Python3.X

 

总结

  我发现Python的函数本质上和其他语言所定义的函数基本相同,有些语法形式上不同。Python独特的动态参数,为函数编写和调用带来了很大的方便,不像JAVA中使用泛型那么复杂。

转载于:https://www.cnblogs.com/zhangss/p/8433041.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值