八、Python的函数编程(之二)

最后更新于:2022-04-01 21:47:32

## 八、Python的函数编程(之二) ----From a high schoolstudent's view to learn Python 关键字: python 高中生学编程 MIT公开课视频Python函数编程 递归 递归函数 递归调用 四、Python’s Built-inFunctions Python包含了很多内置的函数: int()、float()、len()、type()、range()、print()、input()、abs()、str()、tuple() 在Python.org上有详细的描述

Built-inFunctions

abs()

divmod()

input()

open()

staticmethod()

all()

enumerate()

int()

ord()

str()

any()

eval_r()

isinstance()

pow()

sum()

basestring()

execfile()

issubclass()

print()

super()

bin()

file()

iter()

property()

tuple()

bool()

filter()

len()

range()

type()

bytearray()

float()

list()

raw_input()

unichr()

callable()

format()

locals()

reduce()

unicode()

chr()

frozenset()

long()

reload()

vars()

classmethod()

getattr()

map()

repr()

xrange()

cmp()

globals()

max()

reversed()

zip()

compile()

hasattr()

memoryview()

round()

__import__()

complex()

hash()

min()

set()

apply()

delattr()

help()

next()

setattr()

buffer()

dict()

hex()

object()

slice()

coerce()

dir()

id()

oct()

sorted()

intern()

这些函数多数都不是经常用到,所以大致了解一下即可,有一些印象,在需要的时候再仔细看看说明。 但在开头列的那几个函数,使用度非常高,应该仔细掌握,主要从以下几个方面进行了解: 函数的作用是什么? 函数的参数是什么类型、缺省参数是什么? 函数的返回值是什么类型? dir([*object*]) Without arguments, return thelist of names in the current local scope. With an argument, attemptto return a list of valid attributes for that object. If the object has a methodnamed __dir__(),this method will be called and must return the list of attributes.This allows objects that implement acustom [__getattr__()](http://docs.python.org/2/reference/datamodel.html) or [__getattribute__()](http://docs.python.org/2/reference/datamodel.html) functionto customize the way [dir()](http://docs.python.org/2/library/functions.html) reportstheir attributes. If the object does notprovide __dir__(),the function tries its best to gather information from theobject’s __dict__ attribute,if defined, and from its type object. The resulting list is notnecessarily complete, and may be inaccurate when the object has acustom [__getattr__()](http://docs.python.org/2/reference/datamodel.html). Thedefault [dir()](http://docs.python.org/2/library/functions.html) mechanismbehaves differently with different types of objects, as it attemptsto produce the most relevant, rather than complete,information: 1. If the object is a moduleobject, the list contains the names of the module’sattributes. 1. If the object is a type orclass object, the list contains the names of its attributes, andrecursively of the attributes of its bases. 1. Otherwise, the list containsthe object’s attributes’ names, the names of its class’sattributes, and recursively of the attributes of its class’s baseclasses. The resulting list is sortedalphabetically. For example: importstruct  dir() *#show the names in the module namespace*  ['__builtins__', '__doc__','__name__', 'struct']  dir(struct) *#show the names in the struct module*  ['Struct', '__builtins__','__doc__', '__file__', '__name__', '__package__', '_clearcache','calcsize', 'error', 'pack', 'pack_into', 'unpack','unpack_from']  classShape(object):        def__dir__(self):           return ['area', 'perimeter','location']  s=Shape()  dir(s)  ['area', 'perimeter','location']  Note Because [dir()](http://docs.python.org/2/library/functions.html) issupplied primarily as a convenience for use at an interactiveprompt, it tries to supply an interesting set of names more than ittries to supply a rigorously or consistently defined set of names,and its detailed behavior may change across releases. For example,metaclass attributes are not in the result list when the argumentis a class. 这是在一本书上找的两个练习: 1. dir()内建函数 - 启动Python 交互式解释器, 通过直接键入 dir() 回车以执行 dir() 内建函数。你看到 什么?显示你看到的每一个列表元素的值,记下实际值和你想像的值 - 你会问, dir() 函数是干什么的?我们已经知道在 dir 后边加上一对括号可以执行 dir() 内建函数, 如果不加括号会如何?试一试。解释器返回给你什么信息? 你认为这个信息表示什么意思 ? - type() 内建函数接收任意的 Python对象做为参数并返回他们的类型。 在解释器中键入 type(dir),看看你得到的是什 - 本练习的最后一部分,我们来瞧一瞧 Python 的文档字符串。 通过dir.__doc__可以访问dir() 内建函数的文档字符串。printdir.__doc__可以显示这个字符串的内容。许多内建 函数,方法,模块及模块属性都有相应的文档字符串。我们希望你在你的代码中也要书写文档 字符串, 它会对使用这些代码的人提供及时方便的帮助。 2. 利用 dir() 找出 sys模块中更多的东西。 1. 启动Python交互解释器,执行dir()函数,然后键入 import sys 以导入 sys 模块。 再次执行 dir() 函数以确认sys 模块被正确的导入。 然后执行 dir(sys) , 你就可以看到 sys模块的所有属性了。 1. 显示 sys 模块的版本号属性及平台变量。记住在属性名前一定要加 sys. ,这表示这个属性是 sys 模块的。其中 version变量保存着你使用的 Python 解释器版本, platform 属性则包含你运行 Python时使用的计算机平台信息。 1. 最后,调用 sys.exit() 函数。这是一种热键之外的另一种退出Python 解释器的方式。 五、常用内建函数的使用 我们先从一些实际的例子着手:


>>>s = 'Hello, world.'

>>>str(s)

'Hello, world.'

>>>repr(s)

"'Hello, world.'"

>>>str(0.1)

'0.1'

>>>repr(0.1)

'0.10000000000000001'

>>>x = 10 * 3.25

>>>y = 200 * 200

>>>s = 'The value of x is ' + repr(x) + ', and y is ' + repr(y) +'...'

>>>print s

The value of x is 32.5, and yis 40000...

>>># The repr() of a string adds string quotes andbackslashes:

... hello = 'hello,world\n'

>>>hellos = repr(hello)

>>>print hellos

'hello, world\n'

>>># The argument to repr() may be any Python object:

... repr((x, y, ('spam','eggs')))

"(32.5, 40000, ('spam','eggs'))"


how do you convert values tostrings? Luckily, Python has ways to convert any value to a string:pass it to the [**repr()**](http://www.python.org/doc//current/library/functions.html) or [**str()**](http://www.python.org/doc//current/library/functions.html) functions. The str() function is meant toreturn representations of values which are fairly human-readable,while repr() is meant to generate representations which can be readby the interpreter (or will force a SyntaxError if there is notequivalent syntax). For objects which don’t have a particularrepresentation for human consumption, str() will return the samevalue as repr(). Many values, such as numbers or structures likelists and dictionaries, have the same representation using eitherfunction. Strings and floating point numbers, in particular, havetwo distinct representations. Here are two ways to write atable of squares and cubes: for x in range(1, 11): ...    print repr(x).rjust(2),repr(x*x).rjust(3), ...    # Note trailing comma on previousline ...    print repr(x*x*x).rjust(4) ... 1  1   1 2  4   8 3  9   27 4  16  64 5 25  125 6 36  216 7 49  343 8 64  512 9 81  729 10 100 1000 for x in range(1,11): ...    print '{0:2d} {1:3d} {2:4d}'.format(x, x*x,x*x*x) ... 1  1   1 2  4   8 3  9   27 4  16  64 5 25  125 6 36  216 7 49  343 8 64  512 9 81  729 10 100 1000 使用print进行格式化的结果输出,注意print、range等函数的使用 常用函数: **abs(x)** Return the absolute value of anumber. The argument may be a plain or long integer or a floatingpoint number. If the argument is a complex number, its magnitude isreturned. **all(iterable)** Return True if all elements ofthe iterable are true (or if the iterable is empty). Equivalentto: def all(iterable): for element in iterable:     if notelement:        return False return True **any(iterable)** Return True if any element ofthe iterable is true. If the iterable is empty, return False.Equivalent to: def any(iterable): for element in iterable:     ifelement:        return True return False New in version 2.5. **bin(x)** Convert an integer number to abinary string. The result is a valid Python expression. If x is nota Python int object, it has to define an __index__() method thatreturns an integer. New in version 2.6. **bool([x])** Convert a value to a Boolean,using the standard truth testing procedure. If x is false oromitted, this returns False; otherwise it returns True. bool isalso a class, which is a subclass of int. Class bool cannot besubclassed further. Its only instances are False andTrue. New in version2.2.1. Changed in version 2.3: If noargument is given, this function returns False. **cmp(x, y)** Compare the two objects x and yand return an integer according to the outcome. The return value isnegative if x < y, zero if x == y and strictlypositive if x > y. **complex([real[,imag]])** Create a complex number withthe value real + imag*j or convert a string or number to a complexnumber. If the first parameter is a string, it will be interpretedas a complex number and the function must be called without asecond parameter. The second parameter can never be a string. Eachargument may be any numeric type (including complex). If imag isomitted, it defaults to zero and the function serves as a numericconversion function like int(), long() and float(). If botharguments are omitted, returns 0j. The complex type is describedin Numeric Types — int, float, long, complex. **dir([object])** Without arguments, return thelist of names in the current local scope. With an argument, attemptto return a list of valid attributes for that object. If the object has a methodnamed __dir__(), this method will be called and must return thelist of attributes. This allows objects that implement a custom__getattr__() or __getattribute__() function to customize the waydir() reports their attributes. If the object does not provide__dir__(), the function tries its best to gather information fromthe object’s __dict__ attribute, if defined, and from its typeobject. The resulting list is not necessarily complete, and may beinaccurate when the object has a custom __getattr__(). The default dir() mechanismbehaves differently with different types of objects, as it attemptsto produce the most relevant, rather than complete,information: If the object is a moduleobject, the list contains the names of the module’sattributes. If the object is a type orclass object, the list contains the names of its attributes, andrecursively of the attributes of its bases. Otherwise, the list containsthe object’s attributes’ names, the names of its class’sattributes, and recursively of the attributes of its class’s baseclasses. The resulting list is sortedalphabetically. For example: import struct dir()   # doctest: +SKIP ['__builtins__', '__doc__','__name__', 'struct'] dir(struct)   # doctest:+NORMALIZE_WHITESPACE ['Struct', '__builtins__','__doc__', '__file__', '__name__', '__package__','_clearcache', 'calcsize', 'error', 'pack', 'pack_into', 'unpack','unpack_from'] class Foo(object): ...    def __dir__(self): ...        return["kan", "ga", "roo"] ... f = Foo() dir(f) ['ga', 'kan', 'roo'] Note Because dir() is suppliedprimarily as a convenience for use at an interactive prompt, ittries to supply an interesting set of names more than it tries tosupply a rigorously or consistently defined set of names, and itsdetailed behavior may change across releases. For example,metaclass attributes are not in the result list when the argumentis a class. **divmod(a, b)** Take two (non complex) numbersas arguments and return a pair of numbers consisting of theirquotient and remainder when using long division. With mixed operandtypes, the rules for binary arithmetic operators apply. For plainand long integers, the result is the same as (a // b, a % b). Forfloating point numbers the result is (q, a % b), where q is usuallymath.floor(a / b) but may be 1 less than that. In any case q * b +a % b is very close to a, if a % b is non-zero it has the same signas b, and 0 <= abs(a % b) >>range(1, 11) [1, 2, 3, 4, 5, 6, 7, 8, 9,10] range(0, 30, 5) [0, 5, 10, 15, 20,25] range(0, 10, 3) [0, 3, 6, 9] range(0, -10, -1) [0, -1, -2, -3, -4, -5, -6, -7,-8, -9] range(0) [] range(1, 0) [] **raw_input([prompt])** If the prompt argument ispresent, it is written to standard output without a trailingnewline. The function then reads a line from input, converts it toa string (stripping a trailing newline), and returns that. When EOFis read, EOFError is raised. Example: s = raw_input('--> ') MontyPython's Flying Circus s "Monty Python's FlyingCircus" If the readline module wasloaded, then raw_input() will use it to provide elaborate lineediting and history features. **repr(object)** Return a string containing aprintable representation of an object. This is the same valueyielded by conversions (reverse quotes). It is sometimes useful tobe able to access this operation as an ordinary function. For manytypes, this function makes an attempt to return a string that wouldyield an object with the same value when passed to eval_r(),otherwise the representation is a string enclosed in angle bracketsthat contains the name of the type of the object together withadditional information often including the name and address of theobject. A class can control what this function returns for itsinstances by defining a __repr__() method. **reversed(seq)** Return a reverse iterator. seqmust be an object which has a __reversed__() method or supports thesequence protocol (the __len__() method and the __getitem__()method with integer arguments starting at 0). New in version 2.4. Changed in version 2.6: Addedthe possibility to write a custom __reversed__() method. **round(x[, n])** Return the floating point valuex rounded to n digits after the decimal point. If n is omitted, itdefaults to zero. The result is a floating point number. Values arerounded to the closest multiple of 10 to the power minus n; if twomultiples are equally close, rounding is done away from 0 (so. forexample, round(0.5) is 1.0 and round(-0.5) is -1.0). **sorted(iterable[, cmp[,key[, reverse]]])** Return a new sorted list fromthe items in iterable. The optional arguments cmp,key, and reverse have the same meaning as those for the list.sort()method (described in section Mutable Sequence Types). cmp specifies a customcomparison function of two arguments (iterable elements) whichshould return a negative, zero or positive number depending onwhether the first argument is considered smaller than, equal to, orlarger than the second argument: cmp=lambda x,y: cmp(x.lower(),y.lower()). The default value is None. key specifies a function of oneargument that is used to extract a comparison key from each listelement: key=str.lower. The default value is None. reverse is a boolean value. Ifset to True, then the list elements are sorted as if eachcomparison were reversed. In general, the key and reverseconversion processes are much faster than specifying an equivalentcmp function. This is because cmp is called multiple times for eachlist element while key and reverse touch each element only once. Toconvert an old-style cmp function to a key function, see theCmpToKey recipe in the ASPN cookbook. New in version 2.4. **str([object])** Return a string containing anicely printable representation of an object. For strings, thisreturns the string itself. The difference with repr(object) is thatstr(object) does not always attempt to return a string that isacceptable to eval_r(); its goal is to return a printable string.If no argument is given, returns the empty string, ''. For more information on stringssee Sequence Types — str, unicode, list, tuple, buffer, xrangewhich describes sequence functionality (strings are sequences), andalso the string-specific methods described in the String Methodssection. To output formatted strings use template strings or the %operator described in the String Formatting Operations section. Inaddition see the String Services section. See alsounicode(). **sum(iterable[,start])** Sums start and the items of aniterable from left to right and returns the total. start defaultsto 0. The iterable‘s items are normally numbers, and are notallowed to be strings. The fast, correct way to concatenate asequence of strings is by calling ''.join(sequence). Note thatsum(range(n), m) is equivalent to reduce(operator.add, range(n), m)To add floating point values with extended precision, seemath.fsum(). New in version 2.3. **tuple([iterable])** Return a tuple whose items arethe same and in the same order as iterable‘s items. iterable may bea sequence, a container that supports iteration, or an iteratorobject. If iterable is already a tuple, it is returned unchanged.For instance, tuple('abc') returns ('a', 'b', 'c') and tuple([1, 2,3]) returns (1, 2, 3). If no argument is given, returns a new emptytuple, (). tuple is an immutable sequencetype, as documented in Sequence Types — str, unicode, list, tuple,buffer, xrange. For other containers see the built in dict, list,and set classes, and the collections module. **type(object)** Return the type of an object.The return value is a type object. The isinstance() built-infunction is recommended for testing the type of anobject. With three arguments, type()functions as a constructor as detailed below. **xrange([start], stop[,step])** This function is very similarto range(), but returns an “xrange object” instead of a list. Thisis an opaque sequence type which yields the same values as thecorresponding list, without actually storing them allsimultaneously. The advantage of xrange() over range() is minimal(since xrange() still has to create the values when asked for them)except when a very large range is used on a memory-starved machineor when all of the range’s elements are never used (such as whenthe loop is usually terminated with break). CPython implementation detail:xrange() is intended to be simple and fast. Implementations mayimpose restrictions to achieve this. The C implementation of Pythonrestricts all arguments to native C longs (“short” Pythonintegers), and also requires that the number of elements fit in anative C long. If a larger range is needed, an alternate versioncan be crafted using the itertools module: islice(count(start,step), (stop-start+step-1)//step). 六、递归 ------ 如果函数包含了对其自身的调用,该函数就是递归的。如果一个新的调用能在相同过程中较早的调用结束之前开始,那么该过程就是递归的。 可以看一段MIT公开课视频: 递归广泛地应用于使用递归函数的数学应用中,类似数学归纳法。 拿阶乘函数的定义来说明: N! == factorial(N) == 1 * 2 * 3... * N  我们可以用这种方式来看阶乘: ~~~ factorial(N) = N! = N * (N-1)! = N * (N-1) * (N-2)! … = N * (N-1) * (N-2) ... * 3 * 2 * 1 ~~~ 我们现在可以看到阶乘是递归的,因为  factorial(N) = N*factorial(N-1) 换句话说,为了获得 factorial(N)的值,需要计算factorial(N-1),而且,为了找到 factorial(N-1),需要计算factorial(N-2)等等。我们现在给出阶乘函数的递归版本。 ~~~ def factorial(n): ...    if n==0 or n==1: ...           return 1 ...    else: ...           returnn*factorial(n-1) ...  factorial(21) 51090942171709440000L factorial(4) 24 factorial(1) 1 factorial(0) 1 ~~~ 特别强调: 1. 递归函数必须有一个终止执行的条件,如我们的例子中,当n=0或者n=1时,会终止;否则,程序将进入一个无限循环的状态,俗称“死循环” 1. 递归虽然使程序看起来非常的简单,但是递归程序如果递归的次数很大的话,将会严重的消耗计算机的内存,甚至可能导致系统的崩溃 下面给出一段视频,里面是以经典的递归问题:斐波那契数列作为例子进行讲解的,值得学习! 【插入视频】 我的更多文章: - [Python程序调试的一些体会](http://blog.sina.com.cn/s/blog_d6cca93e0101ewc9.html)(2013-10-06 22:57:35) - [十四、Python编程计算24点(之二)](http://blog.sina.com.cn/s/blog_d6cca93e0101euxx.html)(2013-10-03 22:18:28) - [十三、Python编程计算24点(之一)](http://blog.sina.com.cn/s/blog_d6cca93e0101eukc.html)![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2015-10-30_5632e1cc04fc3.gif "此博文包含图片") (2013-10-02 22:15:46) - [十二、Python简单数据结构应用(之二)](http://blog.sina.com.cn/s/blog_d6cca93e0101euk8.html)(2013-10-02 22:10:41) - [十一、Python简单数据结构应用(之一)](http://blog.sina.com.cn/s/blog_d6cca93e0101ep9z.html)(2013-09-23 23:31:49) - [十、Python编程解决组合问题(之二)](http://blog.sina.com.cn/s/blog_d6cca93e0101entc.html)![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2015-10-30_5632e1cc04fc3.gif "此博文包含图片") (2013-09-21 23:37:27) - [九、Python编程解决组合问题(之一)](http://blog.sina.com.cn/s/blog_d6cca93e0101ent7.html)(2013-09-21 23:32:54) - [七、Python的函数编程(之一)](http://blog.sina.com.cn/s/blog_d6cca93e0101ekwg.html)![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2015-10-30_5632e1cc04fc3.gif "此博文包含视频") (2013-09-20 23:09:10) - [六、Python的程序流程](http://blog.sina.com.cn/s/blog_d6cca93e0101ejeg.html)(2013-09-19 16:53:58) - [高中生如何学编程](http://blog.sina.com.cn/s/blog_d6cca93e0101e8fn.html)(2013-09-02 19:26:01)
';