찾다
백엔드 개발파이썬 튜토리얼Python 함수 사용법 요약

Python 함수 사용법 요약

Aug 05, 2017 pm 04:15 PM
python기능요약

빈 함수

아무 일도 하지 않는 빈 함수를 정의하려면 pass 문을 사용할 수 있습니다: pass语句:


def nop():    pass

pass语句什么都不做,那有什么用?实际上pass可以用来作为占位符,比如现在还没想好怎么写函数的代码,就可以先放一个pass,让代码能运行起来。

pass还可以用在其他语句里,比如if

小结

定义函数时,需要确定函数名和参数个数;

如果有必要,可以先对参数的数据类型做检查;

函数体内部可以用return随时返回函数结果;

函数执行完毕也没有return语句时,自动return None

函数可以同时返回多个值,但其实就是一个tuple。

 

可变参数

在Python函数中,还可以定义可变参数。顾名思义,可变参数就是传入的参数个数是可变的,可以是1个、2个到任意个,还可以是0个。

*nums表示把nums这个list的所有元素作为可变参数传进去。这种写法相当有用,而且很常见。

关键字参数

可变参数允许你传入0个或任意个参数,这些可变参数在函数调用时自动组装为一个tuple。而关键字参数允许你传入0个或任意个含参数名的参数,这些关键字参数在函数内部自动组装为一个dict。

关键字参数有什么用?它可以扩展函数的功能。比如,在person函数里,我们保证能接收到nameage这两个参数,但是,如果调用者愿意提供更多的参数,我们也能收到。试想你正在做一个用户注册的功能,除了用户名和年龄是必填项外,其他都是可选项,利用关键字参数来定义这个函数就能满足注册的需求。

和可变参数类似,也可以先组装出一个dict,然后,把该dict转换为关键字参数传进去:


>>> extra = {'city': 'Beijing', 'job': 'Engineer'}>>> person('Jack', 24, city=extra['city'], job=extra['job'])
name: Jack age: 24 other: {'city': 'Beijing', 'job': 'Engineer'}

当然,上面复杂的调用可以用简化的写法:


>>> extra = {'city': 'Beijing', 'job': 'Engineer'}>>> person('Jack', 24, **extra)
name: Jack age: 24 other: {'city': 'Beijing', 'job': 'Engineer'}

**extra表示把extra这个dict的所有key-value用关键字参数传入到函数的**kw参数,kw将获得一个dict,注意kw获得的dict是extra的一份拷贝,对kw的改动不会影响到函数外的extra

 

命名关键字参数

对于关键字参数,函数的调用者可以传入任意不受限制的关键字参数。至于到底传入了哪些,就需要在函数内部通过kw检查。

仍以person()函数为例,我们希望检查是否有cityjob参数

如果要限制关键字参数的名字,就可以用命名关键字参数,例如,只接收cityjob作为关键字参数。这种方式定义的函数如下:


def person(name, age, *, city, job):    print(name, age, city, job)

和关键字参数**kw不同,命名关键字参数需要一个特殊分隔符**后面的参数被视为命名关键字参数。

调用方式如下:


>>> person('Jack', 24, city='Beijing', job='Engineer')
Jack 24 Beijing Engineer

如果函数定义中已经有了一个可变参数,后面跟着的命名关键字参数就不再需要一个特殊分隔符*了:


def person(name, age, *args, city, job):    print(name, age, args, city, job)

命名关键字参数必须传入参数名,这和位置参数不同。如果没有传入参数名,调用将报错:


>>> person('Jack', 24, 'Beijing', 'Engineer')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>TypeError: person() takes 2 positional arguments but 4 were given</module></stdin>

参数组合

在Python中定义函数,可以用必选参数、默认参数、可变参数、关键字参数和命名关键字参数,这5种参数都可以组合使用。但是请注意,参数定义的顺序必须是:必选参数、默认参数、可变参数、命名关键字参数和关键字参数。

比如定义一个函数,包含上述若干种参数:


def f1(a, b, c=0, *args, **kw):    print('a =', a, 'b =', b, 'c =', c, 'args =', args, 'kw =', kw)def f2(a, b, c=0, *, d, **kw):    print('a =', a, 'b =', b, 'c =', c, 'd =', d, 'kw =', kw)

在函数调用的时候,Python解释器自动按照参数位置和参数名把对应的参数传进去。


>>> f1(1, 2)
a = 1 b = 2 c = 0 args = () kw = {}>>> f1(1, 2, c=3)
a = 1 b = 2 c = 3 args = () kw = {}>>> f1(1, 2, 3, 'a', 'b')
a = 1 b = 2 c = 3 args = ('a', 'b') kw = {}>>> f1(1, 2, 3, 'a', 'b', x=99)
a = 1 b = 2 c = 3 args = ('a', 'b') kw = {'x': 99}>>> f2(1, 2, d=99, ext=None)
a = 1 b = 2 c = 0 d = 99 kw = {'ext': None}

最神奇的是通过一个tuple和dict,你也可以调用上述函数:


>>> args = (1, 2, 3, 4)>>> kw = {'d': 99, 'x': '#'}>>> f1(*args, **kw)
a = 1 b = 2 c = 3 args = (4,) kw = {'d': 99, 'x': '#'}>>> args = (1, 2, 3)>>> kw = {'d': 88, 'x': '#'}>>> f2(*args, **kw)
a = 1 b = 2 c = 3 d = 88 kw = {'x': '#'}

以,对于任意函数,都可以通过类似func(*args, **kw)


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.        """
        passPython 2.x
pass 문은 아무 작업도 수행하지 않습니다. 그렇다면 무슨 용도일까요? 실제로 pass를 자리 표시자로 사용할 수 있습니다. 예를 들어 함수 코드 작성 방법을 아직 파악하지 못한 경우 pass를 먼저 입력하면 됩니다. 코드가 실행될 수 있다는 것입니다.

pass는 if

Summary

와 같은 다른 문에서도 사용할 수 있습니다. 함수를 정의할 때 함수 이름과 매개변수 수를 결정해야 합니다.

필요한 경우 다음을 수행할 수 있습니다. 먼저 매개변수의 데이터 유형을 확인하세요. 🎜🎜함수 본문 내에서 return을 사용하여 언제든지 함수 결과를 반환할 수 있습니다. 🎜🎜함수가 실행되고 return 문을 사용하면 자동으로 return None이 됩니다. 🎜🎜이 함수는 동시에 여러 값을 반환할 수 있지만 실제로는 튜플입니다. 🎜🎜🎜🎜변수 매개변수🎜🎜Python 함수에서는 변수 매개변수를 정의할 수도 있습니다. 이름에서 알 수 있듯이 가변 매개변수는 전달된 매개변수의 수가 가변적이며 1, 2 또는 임의의 숫자일 수 있거나 0일 수 있음을 의미합니다. 🎜🎜*numsnums 목록의 모든 요소를 ​​변수 매개변수로 전달하는 것을 의미합니다. 이런 글쓰기 방식은 매우 유용하고 매우 일반적입니다. 🎜🎜키워드 매개변수🎜🎜변수 매개변수를 사용하면 0개 또는 임의 개수의 매개변수를 전달할 수 있습니다. 이러한 변수 매개변수는 함수가 호출될 때 자동으로 튜플로 결합됩니다. 키워드 매개변수를 사용하면 매개변수 이름이 포함된 매개변수를 0개 또는 원하는 수만큼 전달할 수 있습니다. 이러한 키워드 매개변수는 함수 내에서 자동으로 사전으로 조합됩니다. 🎜🎜키워드 매개변수는 어떤 용도로 사용되나요? 함수의 기능을 확장할 수 있습니다. 예를 들어, person 함수에서는 nameage 두 매개변수를 수신하도록 보장됩니다. 그러나 호출자가 제공하려는 경우. more 매개변수도 수신할 수 있습니다. 사용자 등록 기능을 수행한다고 가정해 보세요. 필수인 사용자 이름과 나이를 제외하고 다른 모든 것은 선택 사항입니다. 키워드 매개변수를 사용하여 이 기능을 정의하면 등록 요구 사항을 충족할 수 있습니다. 🎜🎜변수 매개변수와 유사하게 사전을 먼저 조합한 다음 사전을 키워드 매개변수로 변환하여 전달할 수도 있습니다. 🎜


🎜

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)  # defaultPython 3.x
🎜물론 위 내용은 다음과 같습니다. 복잡함 호출은 단순화된 방식으로 작성할 수 있습니다: 🎜


🎜

with open('log','r') as f:
       
    ...
🎜**extraextra의 모든 키-값을 의미합니다. dict 키워드 인수를 사용하여 함수의 **kw 매개변수를 전달합니다. kwkw로 얻은 dict를 가져옵니다. extra의 복사본입니다. kw에 대한 변경 사항은 함수 외부의 extra에 영향을 미치지 않습니다. 🎜🎜 🎜🎜이름이 지정된 키워드 매개변수🎜🎜키워드 매개변수의 경우 함수 호출자는 무제한의 키워드 매개변수를 전달할 수 있습니다. 전달된 내용은 함수 내부의 kw를 통해 확인해야 합니다. 🎜🎜그래도 person() 함수를 예로 들어 cityjob 매개변수가 있는지 확인하고 싶습니다🎜🎜원하는 경우 키워드 매개변수 이름을 제한하려면 이름이 지정된 키워드 매개변수를 사용할 수 있습니다. 예를 들어 cityjob만 키워드 매개변수로 수신합니다. 이렇게 정의된 함수는 다음과 같습니다. 🎜


🎜

with open('log1') as obj1, open('log2') as obj2:    pass
🎜 키워드 매개변수 **kw와 달리 명명된 키워드 매개변수에는 특수 구분 기호* 및 *는 명명된 키워드 매개변수로 처리됩니다. 🎜🎜호출 방법은 다음과 같습니다. 🎜


🎜

# 普通条件语句if 1 == 1:
    name = 'wupeiqi'else:
    name = 'alex'
   # 三元运算name = 'wupeiqi' if 1 == 1 else 'alex'
🎜함수 정의에 이미 변수 매개변수가 있는 경우 다음 명명된 키워드 매개변수에는 더 이상 특수 구분 기호*: 🎜


🎜

# ###################### 普通函数 ####################### 定义函数(普通方式)def func(arg):    return arg + 1   
# 执行函数result = func(123)   
# ###################### lambda ######################
   # 定义函数(lambda表达式)my_lambda = lambda arg : arg + 1   
# 执行函数result = my_lambda(123)
🎜이름이 지정된 키워드 매개변수는 매개변수 이름에 전달되어야 하며 이는 위치 매개변수와 다릅니다. 매개변수 이름이 전달되지 않으면 호출 시 오류가 보고됩니다. 🎜


🎜

def fact(n):    if n==1:        return 1    return n * fact(n - 1)
🎜매개변수 조합🎜🎜Python에서 함수를 정의하세요. 필수 매개변수, 기본 매개변수, 변수를 사용할 수 있습니다. 매개변수, 키워드 매개변수, 명명된 키워드 매개변수 등 5개의 매개변수를 조합하여 사용할 수 있습니다. 그러나 매개변수 정의의 순서는 필수 매개변수, 기본 매개변수, 변수 매개변수, 명명된 키워드 매개변수 및 키워드 매개변수여야 합니다. 🎜🎜예를 들어 위의 매개변수가 포함된 함수를 정의합니다. 🎜


🎜

>>> fact(1)1
>>> fact(5)120
>>> fact(100)93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000

===> fact(5)===> 5 * fact(4)===> 5 * (4 * fact(3))===> 5 * (4 * (3 * fact(2)))===> 5 * (4 * (3 * (2 * fact(1))))===> 5 * (4 * (3 * (2 * 1)))===> 5 * (4 * (3 * 2))===> 5 * (4 * 6)===> 5 * 24
===> 120
🎜함수가 호출되면 Python 인터프리터는 매개변수 위치에 따라 해당 매개변수를 자동으로 전달하고 매개변수 이름을 입력하세요. 🎜


🎜

def fact(n):    return fact_iter(n, 1)def fact_iter(num, product):    if num == 1:        return product    return fact_iter(num - 1, num * product)
🎜가장 놀라운 점은 튜플과 dict를 통해 위 함수를 호출할 수도 있다는 것입니다: 🎜


🎜

===> fact_iter(5, 1)===> fact_iter(4, 5)===> fact_iter(3, 20)===> fact_iter(2, 60)===> fact_iter(1, 120)===> 120
🎜그래서 따라서 어떤 함수에 대해서도 func(*args, **kw)와 유사한 형식으로 호출할 수 있습니다. 해당 매개변수는 다음과 같이 정의됩니다. 🎜🎜🎜요약🎜🎜Python의 함수는 간단한 호출을 구현할 수 있을 뿐만 아니라 매우 복잡한 매개변수도 전달할 수 있는 매우 유연한 매개변수 형식을 가지고 있습니다. 🎜🎜기본 매개변수는 불변 객체를 사용해야 합니다. 가변 객체인 경우 프로그램 실행 시 논리 오류가 발생합니다! 🎜🎜가변 매개변수와 키워드 매개변수 정의 구문에 주의하세요.🎜

*args是可变参数,args接收的是一个tuple;

**kw是关键字参数,kw接收的是一个dict。

以及调用函数时如何传入可变参数和关键字参数的语法:

可变参数既可以直接传入:func(1, 2, 3),又可以先组装list或tuple,再通过*args传入:func(*(1, 2, 3))

关键字参数既可以直接传入:func(a=1, b=2),又可以先组装dict,再通过**kw传入:func(**{'a': 1, 'b': 2})

使用*args**kw是Python的习惯写法,当然也可以用其他参数名,但最好使用习惯用法。

命名的关键字参数是为了限制调用者可以传入的参数名,同时可以提供默认值。

定义命名的关键字参数在没有可变参数的情况下不要忘了写分隔符*,否则定义的将是位置参数。

 

内置函数

注:查看详细猛击这里

 

文件操作函数

open函数,该函数用于文件处理

操作文件时,一般需要经历如下步骤:

  • 打开文件

  • 操作文件

一、打开文件

  文件句柄 = open('文件路径''模式')

打开文件时,需要指定文件路径和以何等方式打开文件,打开后,即可获取该文件句柄,日后通过此文件句柄对该文件操作。

打开文件的模式有:

  • r,只读模式(默认)。

  • w,只写模式。【不可读;不存在则创建;存在则删除内容;】

  • a,追加模式。【可读;   不存在则创建;存在则只追加内容;】

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

  • r+,可读写文件。【可读;可写;可追加】

  • w+,写读

  • a+,同a

"U"表示在读取时,可以将 \r \n \r\n自动转换成 \n (与 r 或 r+ 模式同使用)

  • rU

  • r+U

"b"表示处理二进制文件(如:FTP发送上传ISO镜像文件,linux可忽略,windows处理二进制文件时需标注)

  • rb

  • wb

  • ab

 

二、操作


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.        """
        passPython 2.x

python 2.0


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)  # defaultPython 3.x

python3.0

三、管理上下文

为了避免打开文件后忘记关闭,可以通过管理上下文,即:


with open('log','r') as f:
       
    ...

如此方式,当with代码块执行完毕时,内部会自动关闭并释放文件资源。

在Python 2.7 后,with又支持同时对多个文件的上下文进行管理,即:


with open('log1') as obj1, open('log2') as obj2:    pass

lambda表达式

学习条件运算时,对于简单的 if else 语句,可以使用三元运算来表示,即:


# 普通条件语句if 1 == 1:
    name = 'wupeiqi'else:
    name = 'alex'
   # 三元运算name = 'wupeiqi' if 1 == 1 else 'alex'

对于简单的函数,也存在一种简便的表示方式,即:lambda表达式


# ###################### 普通函数 ####################### 定义函数(普通方式)def func(arg):    return arg + 1   
# 执行函数result = func(123)   
# ###################### lambda ######################
   # 定义函数(lambda表达式)my_lambda = lambda arg : arg + 1   
# 执行函数result = my_lambda(123)

lambda存在意义就是对简单函数的简洁表示!

 

递归


def fact(n):    if n==1:        return 1    return n * fact(n - 1)

递归函数的优点是定义简单,逻辑清晰。理论上,所有的递归函数都可以写成循环的方式,但循环的逻辑不如递归清晰。

使用递归函数需要注意防止栈溢出。在计算机中,函数调用是通过栈(stack)这种数据结构实现的,每当进入一个函数调用,栈就会加一层栈帧,每当函数返回,栈就会减一层栈帧。由于栈的大小不是无限的,所以,递归调用的次数过多,会导致栈溢出。可以试试fact(1000)


>>> fact(1)1
>>> fact(5)120
>>> fact(100)93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000

===> fact(5)===> 5 * fact(4)===> 5 * (4 * fact(3))===> 5 * (4 * (3 * fact(2)))===> 5 * (4 * (3 * (2 * fact(1))))===> 5 * (4 * (3 * (2 * 1)))===> 5 * (4 * (3 * 2))===> 5 * (4 * 6)===> 5 * 24
===> 120

解决递归调用栈溢出的方法是通过尾递归优化,事实上尾递归和循环的效果是一样的,所以,把循环看成是一种特殊的尾递归函数也是可以的。

尾递归是指,在函数返回的时候,调用自身本身,并且,return语句不能包含表达式。这样,编译器或者解释器就可以把尾递归做优化,使递归本身无论调用多少次,都只占用一个栈帧,不会出现栈溢出的情况。

上面的fact(n)函数由于return n * fact(n - 1)引入了乘法表达式,所以就不是尾递归了。要改成尾递归方式,需要多一点代码,主要是要把每一步的乘积传入到递归函数中:


def fact(n):    return fact_iter(n, 1)def fact_iter(num, product):    if num == 1:        return product    return fact_iter(num - 1, num * product)

可以看到,return fact_iter(num - 1, num * product)仅返回递归函数本身,num - 1num * product在函数调用前就会被计算,不影响函数调用。

fact(5)对应的fact_iter(5, 1)的调用如下:


===> fact_iter(5, 1)===> fact_iter(4, 5)===> fact_iter(3, 20)===> fact_iter(2, 60)===> fact_iter(1, 120)===> 120

尾递归调用时,如果做了优化,栈不会增长,因此,无论多少次调用也不会导致栈溢出。

遗憾的是,大多数编程语言没有针对尾递归做优化,Python解释器也没有做优化,所以,即使把上面的fact(n)函数改成尾递归方式,也会导致栈溢出。

小结

使用递归函数的优点是逻辑简单清晰,缺点是过深的调用会导致栈溢出。

针对尾递归优化的语言可以通过尾递归防止栈溢出。尾递归事实上和循环是等价的,没有循环语句的编程语言只能通过尾递归实现循环。

Python标准的解释器没有针对尾递归做优化,任何递归函数都存在栈溢出的问题。

汉诺塔:


#!/usr/bin/env python3# -*- coding: utf-8 -*-# 利用递归函数计算阶乘# N! = 1 * 2 * 3 * ... * Ndef fact(n):    if n == 1:        return 1    return n * fact(n-1)print('fact(1) =', fact(1))print('fact(5) =', fact(5))print('fact(10) =', fact(10))# 利用递归函数移动汉诺塔:def move(n, a, b, c):    if n == 1:        print('move', a, '-->', c)        return
    move(n-1, a, c, b)    print('move', a, '-->', c)
    move(n-1, b, a, c)

move(4, 'A', 'B', 'C')

위 내용은 Python 함수 사용법 요약의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
어레이는 파이썬으로 과학 컴퓨팅에 어떻게 사용됩니까?어레이는 파이썬으로 과학 컴퓨팅에 어떻게 사용됩니까?Apr 25, 2025 am 12:28 AM

Arraysinpython, 특히 비밀 복구를위한 ArecrucialInscientificcomputing.1) theaRearedFornumericalOperations, DataAnalysis 및 MachinELearning.2) Numpy'SimplementationIncensuressuressurations thanpythonlists.3) arraysenablequick

같은 시스템에서 다른 파이썬 버전을 어떻게 처리합니까?같은 시스템에서 다른 파이썬 버전을 어떻게 처리합니까?Apr 25, 2025 am 12:24 AM

Pyenv, Venv 및 Anaconda를 사용하여 다양한 Python 버전을 관리 할 수 ​​있습니다. 1) PYENV를 사용하여 여러 Python 버전을 관리합니다. Pyenv를 설치하고 글로벌 및 로컬 버전을 설정하십시오. 2) VENV를 사용하여 프로젝트 종속성을 분리하기 위해 가상 환경을 만듭니다. 3) Anaconda를 사용하여 데이터 과학 프로젝트에서 Python 버전을 관리하십시오. 4) 시스템 수준의 작업을 위해 시스템 파이썬을 유지하십시오. 이러한 도구와 전략을 통해 다양한 버전의 Python을 효과적으로 관리하여 프로젝트의 원활한 실행을 보장 할 수 있습니다.

표준 파이썬 어레이를 통해 Numpy Array를 사용하면 몇 가지 장점은 무엇입니까?표준 파이썬 어레이를 통해 Numpy Array를 사용하면 몇 가지 장점은 무엇입니까?Apr 25, 2025 am 12:21 AM

Numpyarrayshaveseveraladvantagesstandardpythonarrays : 1) thearemuchfasterduetoc 기반 간증, 2) thearemorememory-refficient, 특히 withlargedatasets 및 3) wepferoptizedformationsformationstaticaloperations, 만들기, 만들기

어레이의 균질 한 특성은 성능에 어떤 영향을 미칩니 까?어레이의 균질 한 특성은 성능에 어떤 영향을 미칩니 까?Apr 25, 2025 am 12:13 AM

어레이의 균질성이 성능에 미치는 영향은 이중입니다. 1) 균질성은 컴파일러가 메모리 액세스를 최적화하고 성능을 향상시킬 수 있습니다. 2) 그러나 유형 다양성을 제한하여 비 효율성으로 이어질 수 있습니다. 요컨대, 올바른 데이터 구조를 선택하는 것이 중요합니다.

실행 파이썬 스크립트를 작성하기위한 모범 사례는 무엇입니까?실행 파이썬 스크립트를 작성하기위한 모범 사례는 무엇입니까?Apr 25, 2025 am 12:11 AM

tocraftexecutablepythonscripts, 다음과 같은 비스트 프랙티스를 따르십시오 : 1) 1) addashebangline (#!/usr/bin/envpython3) tomakethescriptexecutable.2) setpermissionswithchmod xyour_script.py.3) organtionewithlarstringanduseifname == "__"

Numpy 배열은 배열 모듈을 사용하여 생성 된 배열과 어떻게 다릅니 까?Numpy 배열은 배열 모듈을 사용하여 생성 된 배열과 어떻게 다릅니 까?Apr 24, 2025 pm 03:53 PM

numpyarraysarebetterfornumericaloperations 및 multi-dimensionaldata, mumemer-efficientArrays

Numpy Array의 사용은 Python에서 어레이 모듈 어레이를 사용하는 것과 어떻게 비교됩니까?Numpy Array의 사용은 Python에서 어레이 모듈 어레이를 사용하는 것과 어떻게 비교됩니까?Apr 24, 2025 pm 03:49 PM

numpyarraysarebetterforheavynumericalcomputing, whilearraymoduleisiMoresuily-sportainedprojectswithsimpledatatypes.1) numpyarraysofferversatively 및 formanceforgedatasets 및 complexoperations.2) Thearraymoduleisweighit 및 ep

CTYPES 모듈은 파이썬의 어레이와 어떤 관련이 있습니까?CTYPES 모듈은 파이썬의 어레이와 어떤 관련이 있습니까?Apr 24, 2025 pm 03:45 PM

ctypesallowscreatingandmanipulatingC-stylearraysinPython.1)UsectypestointerfacewithClibrariesforperformance.2)CreateC-stylearraysfornumericalcomputations.3)PassarraystoCfunctionsforefficientoperations.However,becautiousofmemorymanagement,performanceo

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

WebStorm Mac 버전

WebStorm Mac 버전

유용한 JavaScript 개발 도구

DVWA

DVWA

DVWA(Damn Vulnerable Web App)는 매우 취약한 PHP/MySQL 웹 애플리케이션입니다. 주요 목표는 보안 전문가가 법적 환경에서 자신의 기술과 도구를 테스트하고, 웹 개발자가 웹 응용 프로그램 보안 프로세스를 더 잘 이해할 수 있도록 돕고, 교사/학생이 교실 환경 웹 응용 프로그램에서 가르치고 배울 수 있도록 돕는 것입니다. 보안. DVWA의 목표는 다양한 난이도의 간단하고 간단한 인터페이스를 통해 가장 일반적인 웹 취약점 중 일부를 연습하는 것입니다. 이 소프트웨어는

SublimeText3 영어 버전

SublimeText3 영어 버전

권장 사항: Win 버전, 코드 프롬프트 지원!

에디트플러스 중국어 크랙 버전

에디트플러스 중국어 크랙 버전

작은 크기, 구문 강조, 코드 프롬프트 기능을 지원하지 않음

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기