python 函数 详解(一)


1 def is executable code. Python functions are written with a new statement, the

def. Unlike functions in compiled languages such as C, def is an executable statement—
your function does not exist until Python reaches and runs the def. In fact,
it’s legal (and even occasionally useful) to nest def statements inside if statements,
while loops, and even other defs. In typical operation, def statements are coded in
module files and are naturally run to generate functions when a module file is first

imported.


Python使用def来声明一个函数。def是可执行的,并且只有执行了def,这个函数才是可用的,

这一点上,与编译型语言,比如C语言是不同的。可以把def声明内嵌到if语句、while循环甚至

其他函数声明里面。一般情况下,函数声明会被放到模块文件中,当我们再其他文件中import

这个模块的时候,函数声明会自然的执行,生成我们需要的函数。

if test:
def func():                   # Define func this way
...
else:
def func():                  # Or else this way
...
...
func()                         # Call the version selected and built


2 def creates an object and assigns it to a name. When Python reaches and runs
a def statement, it generates a new function object and assigns it to the function’s
name. As with all assignments, the function name becomes a reference to the function
object. There’s nothing magic about the name of a function—as you’ll see,
the function object can be assigned to other names, stored in a list, and so on.
Function objects may also have arbitrary user-defined attributes attached to them
to record data.

def执行的时候会创建一个对象,并把函数名作为对象名字。跟所有的赋值操作一样,函数名

会变成这个对象的引用。这个对象跟其他的普通对象完全一样,你可以给它重新命名,把它

放到List中去,这些操作都是可以的。你也可以给它添加任意的属性来保存数据。


othername = func     # Assign function object
othername()              # Call func again


def func(): ... # Create function object
func()            # Call object
func.attr = value     # Attach attributes


3 lambda creates an object but returns it as a result. Functions may also be created
with the lambda expression, a feature that allows us to in-line function definitions
in places where a def statement won’t work syntactically (this is a more advanced
concept that we’ll defer until Chapter 19).


4 return sends a result object back to the caller. When a function is called, the
caller stops until the function finishes its work and returns control to the caller.
Functions that compute a value send it back to the caller with a return statement;
the returned value becomes the result of the function call.

return语句返回一个值给调用者。


5 yield sends a result object back to the caller, but remembers where it left
off.
Functions known as generators may also use the yield statement to send back
a value and suspend their state such that they may be resumed later, to produce a
series of results over time. This is another advanced topic covered later in this part
of the book.


6 global declares module-level variables that are to be assigned. By default, all
names assigned in a function are local to that function and exist only while the
function runs. To assign a name in the enclosing module, functions need to list it
in a global statement. More generally, names are always looked up in scopes—
places where variables are stored—and assignments bind names to scopes.


默认情况下,函数体内所有的变量都是局部变量,函数执行完后即消失。如果想声明

一个模块级别的全局变量,那么需要一个全局的声明。


7 nonlocal declares enclosing function variables that are to be assigned. Similarly,
the nonlocal statement added in Python 3.0 allows a function to assign a
name that exists in the scope of a syntactically enclosing def statement. This allows

enclosing functions to serve as a place to retain state—information remembered
when a function is called—without using shared global names.

nonlocal 声明封闭函数变量。Python3.0允许声明一个函数作用域中的变量,这个变量

具有记忆功能,会记住上次函数执行时变量的值。这个如同在C函数中声明的static变量。


8 Arguments are passed by assignment (object reference). In Python, arguments
are passed to functions by assignment (which, as we’ve learned, means by object
reference). As you’ll see, in Python’s model the caller and function share objects
by references, but there is no name aliasing. Changing an argument name within
a function does not also change the corresponding name in the caller, but changing
passed-in mutable objects can change objects shared by the caller.

以引用的方式传递参数。具体参考上一篇博文《python 函数参数传递

9 Arguments, return values, and variables are not declared. As with everything
in Python, there are no type constraints on functions. In fact, nothing about a
function needs to be declared ahead of time: you can pass in arguments of any type,
return any kind of object, and so on. As one consequence, a single function can
often be applied to a variety of object types—any objects that sport a compatible
interface (methods and expressions) will do, regardless of their specific types.

参数、返回值以及函数中的所有的变量都需要事先声明其类型。你可以传递任意类型

的参数给一个函数,返回任意类型的值。


函数声明:

def <name>(arg1, arg2,... argN):
<statements>

Technically, a function without a return statement returns the None object automatically,
but this return value is usually ignored.

技术上,如果一个函数没有return语句,那么函数会自动返回None对象,调用者一般会忽略这个

返回值。


In other words, what our times function means and does depends on what we pass into
it. This is a core idea in Python (and perhaps the key to using the language well), which
we’ll explore in the next section.


def intersect(seq1, seq2):
res = []                                    # Start empty
for x in seq1:                         # Scan seq1
if x in seq2:                   # Common item?
res.append(x)      # Add to end
return res

>>> s1 = "SPAM"
>>> s2 = "SCAM"
>>> intersect(s1, s2)           # Strings
['S', 'A', 'M']


>>> x = intersect([1, 2, 3], (1, 4))          # Mixed types
>>> x                                                         # Saved result object
[1]





























































  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值