You are on page 1of 41

Python

def

Functions


:

Python

def (function)

-

:
()
,
()

:
:

:

.

def

def: ( define
)
name: , (identifier)
(arg1, arg2, argN): (parameters) (
(arguments)) ()
statements: block

return: ,
value ()
value: ( )
()
.
.

def

-1

return x*y 2
Enter


:
print(ginomeno(2,4))
.

def

-2
(parameter):



(arguments):


(
)

()

(
)
:
2x
4y
.

def

-3

a, b
x & y
. x, y () 3 & 5

def

-4

:
()

()
( c)
.

def

-5

print; ;

;
: (, ,
.)

def

-1

1. / RETURN

return

print()
return ()
None

def

-2

2. / RETURN

( ) return

def

-3

3. / RETURN
return

def

-4

4. / RETURN

return

def

-5

5.






(override)

print
;
.

Python

Python ; - 1
def

( )
Function object

fname

func()

def
(assignment, =) /

2 :
.

Python ; - 2
(1)
, (.
)

Python ; - 3
(2)

power = dynamh

power


Scope

(Variable scope)

-1

(local)
()

(local)
(local scope)
(local
namespace)

(Global)

(.
)
(global)


(global namespace)

: res, x
: s1, s2
: ;;

-2

-
(nonlocal variable)


-
(nonlocal)
.

-: first, last
nonlocal first & last
nested


nonlocal -
first, last

intersect

: ;
LEGB
LEGB = Local / Enclosing / Global / Built-in
H Python 4 :
Local ()

Enclosing ()

Global ()

Built-in ()
standard / / , .
.

LEGB

: local
,
global nonlocal
.

-1

global

( )
: Global
Z, Y: Locals

Global
Local

88 (global)
.

-2


global
: Global
99

Global
y & z
global
LEGB
.

-3

global

-4



local
Global
Local func1()
Non-local func2()
88

-5

has_upper local

checkPass

checkUpper
nonlocal



checkPass

has_lower &
has_num


Arguments

(Arguments)

-1


(. (local)
)

(Arguments)

-2



() - (Immutable) (. ,
):


.

() (Mutable) :



.
.

- 1

(1)

- 1

(2) :

- 1

(3)
a (immutable)
4
b (mutable)
:
b
L

- 1

(4)

(5)

:
L:
.



(mutable)


;
():

. myfunc(X, L) myfunc(X, L[:])


():


.
:


:

Python

You might also like