253
PYTHON 함함 함함함함 Moon Yong Joon

파이썬 함수 이해하기

Embed Size (px)

Citation preview

PowerPoint

Python Moon Yong Joon

2.1

Moon Yong Joon2

Function 3

()Return 4

comment __doc__

5

-None Return None

6

None

7

-return Tuple .

8

Function

context . self : cls: class Foo() : def __init__(self,name=None) : self.name = name bar = external_bardef external_bar(self,lastname): self.lastname = lastname return self.name+ " " + self.lastname

__self__ bound __self__

11

Function

def add(x,y) : return x+yadddef add(x,y) : return x+y{x : None, y:None}

function type code type

function type code typefunc_code.func_code : code type. .

function type AttributeDescription__doc__ doc __name__ __code__ byte code code __defaults__ arguments default __globals__ __closure__ closure context

function type : Function type

Code type code AttributeDescriptionco_argcount number of arguments (not including * or ** args)co_codestring of raw compiled bytecodeco_consts tuple of constants used in the bytecodco_filename name of file in which this code object was createdco_firstlineno number of first line in Python source codeco_flags bitmap: 1=optimized|2=newlocals|4=*arg|8=**argco_lnotab encoded mapping of line numbers to bytecode indicesco_namename with which this code object was definedco_namestuple of names of local variablesco_nlocalsnumber of local variablesco_stacksizevirtual machine stack space requiredco_varnamestuple of names of arguments and local variables

Code type : __code__ code type

inspect : Inspect functionDescriptioninspect.getdoc(object) object doc inspect.getsourcefile(object) object (0 inspect.getmodule(object) object inspect.getsource(object) object inspect.getsourcelines(object) object inspect.getargspec(func) argument inspect.getcallargs(func[, *args][, **kwds]) argument

inspect : Inspect

2.2

Moon Yong Joon21

Function 22

def add(x,y) : return x+yadddef add(x,y) : return x+y{x : None, y:None}

23

: function type code type

function type code typefunc_code.func_code : code type. .24

Function 25

Function class 3 function Python 2Python 3a_function.func_name/__name__a_function.__name__a_function.func_doc/__doc__a_function.__doc__a_function.func_defaults/__defauts__a_function.__defaults__a_function.func_dict/__dict__a_function.__dict__a_function.func_closure/__closure__a_function.__closure__a_function.func_globals/__globals__a_function.__globals__a_function.func_code/__code__a_function.__code__

26

special (code, closure, globals ) 27

inspect : Inspect functionDescriptioninspect.getdoc(object) object doc inspect.getsourcefile(object) object (0 inspect.getmodule(object) object inspect.getsource(object) object inspect.getsourcelines(object) object inspect.getargspec(func) argument inspect.getcallargs(func[, *args][, **kwds]) argument inspect.signature() inspect.getframeinfo(frame) frame

28

inspect : argument Inspect argument

29

Inspect getcallargs getcallargs(,,)

30

inspect :signature 3 annotation signature( ) 31

Code 32

Code code AttributeDescriptionco_argcount number of arguments (not including * or ** args)Co_cellvars?co_codestring of raw compiled bytecodeco_consts tuple of constants used in the bytecodco_filename name of file in which this code object was createdco_firstlineno number of first line in Python source codeco_flags bitmap: 1=optimized|2=newlocals|4=*arg|8=**arg co_freevars co_kwonlyargcount?co_lnotab encoded mapping of line numbers to bytecode indicesco_namename with which this code object was definedco_namestuple of names of local variablesco_nlocalsnumber of local variablesco_stacksizevirtual machine stack space requiredco_varnamestuple of names of arguments and local variables

33

Code , __code__(code ) 34

2.3

Moon Yong Joon35

36

( ( ) )

()

def ( ) : (return/yield)objectfunctioncode 37

Stack stack 1 2 3 4Stack load38

Frame class 39

frame class frame class f_backnext outer frame object (this frames caller)f_builtinsbuiltins namespace seen by this framef_codecode object being executed in this framef_globalsglobal namespace seen by this framef_lastiindex of last attempted instruction in bytecodef_linenocurrent line number in Python source codef_localslocal namespace seen by this framef_tracetracing function for this frame, orNone

40

frame frame 41

frame 42

2.4 1

Moon Yong Joon43

1 44

First Class Object First Class .(variable) (parameter) (return value)

function 45

First Class Object : 1 (first class object) (runtime) (anonymous)

46

First Class Object :

()

47

First Class Object :

48

First Class Object : return

49

2.5 Function scope

Moon Yong Joon50

Function variable scope51

Scoping . Local > global > Built-in Global/nonlocal

globalBuilt-in

Scope Namespacelocallocal52

-scope dictionary / locals()

#53

locals() locals()

dict

54

globals() global module . Import global global 2

55

global : immutable global

56

2.6

Moon Yong Joon57

Parameter/argment58

4 //(x,y,z) / / / 59

(position)60

(key/value) key/value

61

(key/value)62

key=value

63

64

:65

Default default __defaults__ (tuple) def (k= 10) __defaults__(10,)66

-

add {x: 10, y:None}# add {x: 1, y: 20}# add {x: 10, y: 20}

67

default 68

Default None def f(a, l=[]) : l.append(a) return lf(1)f(2)f(3){ a:1, l :[1]} { a:2, l :[1,2]}{ a:2, l :[1,2,3]}f(1) f(2) f(3) List .def f(a, l=None) : l = [] l.append(a) return l

69

Default defaults tuple tuple

70

Default mutable default default .

71

(tuple)72

*args namespace args(key), (value)

73

args key tuple value

74

(dict)75

- **kargs keyword

76

77

, , , 78

/ 79

: +

80

: +

81

/ 82

: *args, **kargs *args **kargs

83

: list *args, **kargs (python 3. list(kargs.values()) )

84

: dict

85

, / 86

87

unpack88

dict *args tuple, **kargs dict

89

Unpack

90

unpack tuple/list * unpack

Python3 dict list

91

unpack dict ** unpack

92

tuple 93

tuple tuple *args call by sharing

94

*args .

95

Dict 96

dict dict dict dict

call by sharing 97

**kwargs ** dict

98

2.7

Moon Yong Joon99

100

Global : (global ) {add: function }{x:None, y:None}{x:5, y:5}

globallocal()local()

101

(global) {add: function , add_args: function}{func:None, x:None, y:None}{func: add, x:5, y:5}globallocal()local()

102

103

Lambda

104

105

() (iteration, generation) 106

stack

107

Iteration : sequence iter() iterator

108

Iteration : sequence iter() iterator

109

Generation : comprehension Generator comprehension exception

110

Generation :function exception

111

2.8

Moon Yong Joon112

Generator 113

Generator generator next next

114

Generator : Yield

115

Generator : Return Yield (next()) exception

116

Coroutine 117

Coroutine : send yield send

Yield send 118

Generator : Generator send

( )119

2.9

Moon Yong Joon120

121

Lambda Lambda (return )

Lambda : () 122

Lambda Lambda (return )

Lambda :

123

tuple

Lambda namespace124

Namespace scope lambda namespace

Local > global> builtin

125

Parameter 126

/Lambda

127

- Lambda *args

128

/Lambda **kargs dict **d **kargs = **d / kargs

129

If 130

Lambda if Lambda if True if lambda :(if True) if else (False )

131

132

Lambda Lambda and/or and :

or : 133

Lambda :

134

List Comprehensions135

Comprehensions Lambda

136

: conprehensionLambda comprehensions lambda

137

Nested lambda138

lambda Lambda

139

:lambda140

Lambda lambda

141

2.9

Moon Yong Joon142

Lambda : partial143

Lambda curry lambda lambda

144

Curry : partial145

: Curry

f11(1) g11(2) h11 (3,4,5) (1,2,3,4,5)

146

functools: partial147

: functools functools partial Partial (1,2,3,4)

148

2.10

Moon Yong Joon149

150

dict

151

152

.

153

.

154

155

2.10

Moon Yong Joon156

High Order Function157

High Order Function (higher-order function), , : . : 158

/ (higher-order function), ,

159

Map 160

map map(f, iterable) (f) (iterable) f

161

map : map list NotesPython 2Python 3map(a_function,'PapayaWhip')list(map(a_function,'PapayaWhip'))map(None,'PapayaWhip')list('PapayaWhip')map(lambdax:x+1,range(42))[x+1forxinrange(42)]foriinmap(a_function,a_sequence):no change[iforiinmap(a_function,a_sequence)]no change

162

reduce 163

reduce : reduce functools NotesPython 2Python 3reduce(a,b,c)from functools import reducereduce(a, b, c)

164

reduce reduce(f, iterable) (f) (iterable) f

165

filter166

filter filter(f, iterable) (f) (iterable) f filter

167

filter : list NotesPython 2Python 3filter(a_function,a_sequence)list(filter(a_function,a_sequence))list(filter(a_function,a_sequence))no changefilter(None,a_sequence)[iforiina_sequenceifi]foriinfilter(None,a_sequence):no change[iforiinfilter(a_function,a_sequence)]no change

168

2.11Nested

Moon Yong Joon169

Nested Function170

171

172

, mutable

173

2.12

Moon Yong Joon174

Closure context175

Closure . variable scope .

Closure context -> 176

Closure context Closure

__closure__ func_closureClosurecontextcell_contents177

Closure : ContextContextLocalLocalIntFloatstringImmutable

178

Closure : __closure__

179

Closure : Python 3 nonlocal 180

181

bubbling12N

182

183

f1(f2)(f3) f1(f2(f3))

184

185

() ( ) return ( ) return

*args, **kargs 186

add ()

187

add ()

188

xxxx

Moon Yong Joon

Built-in function list

2.X built-in FunctionsBuilt-in Functionsabs()divmod()input()open()staticmethod()all()enumerate()int()ord()str()any()eval()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()delattr()help()next()setattr()dict()hex()object()slice()dir()id()oct()sorted()

3.X built-in Functions

Built-in Functionsabs()dict()help()min()setattr()all()dir()hex()next()slice()any()divmod()id()object()sorted()ascii()enumerate()input()oct()staticmethod()bin()eval()int()open()str()bool()exec()isinstance()ord()sum()bytearray()filter()issubclass()pow()super()bytes()float()iter()print()tuple()callable()format()len()property()type()chr()frozenset()list()range()vars()classmethod()getattr()locals()repr()zip()compile()globals()map()reversed()__import__()complex()hasattr()max()round()delattr()hash()memoryview()set()

help, ,

>>>help(vars) vars(...) vars([object]) -> dictionary Without arguments, equivalent to locals(). With an argument, equivalent to object.__dict__.

Type >>> int

>>> float

>>> str

>>> list

>>> dict

>>> tuple

>>> set

>>> complex>> type(1.1) >> l= [1,2,3,4]>>> iter(l)

>>> li = iter(l)>>> li.next()1>>> li.next()2>>> li.next()3>>> li.next()4>>> li.next()Traceback (most recent call last): File "", line 1, in StopIteration>>>

Iterable range range(, , ) range(10) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

range(1,10) # [1, 2, 3, 4, 5, 6, 7, 8, 9]

range(1,10,2) #[1, 3, 5, 7, 9]

/

issubclass/isinstance >>> issubclass(list,object)True>>> list.__bases__(,)>>> issubclass(list, type)False>>> issubclass() : __bases__ isinstance() : __ class__ >>> isinstance(list, type)True>>> list.__class__

>>> >>> isinstance(list, object)True>>> issubclass isinstance

id/hash >>>id(b)275969936

>>>id(B)275931744

>>>hash(bb) 17292299

>>>cc = bb

>>>hash(cc)17292299

>>>hash(bb) == hash(cc)True

id() hash() hash integer

object.x getattr()object.x = value setattr()del(object.x) delattr()

getattr(object,name[,default])setattr(object,name,value)delattr(object,name)hasattr(object,name) # ( )callable(object) #

: 1

class A(): def __init__(self, name,age) : self.name = name self.age = age a = A('dahl',50)

if hasattr(a,"name") : print getattr(a,"name") setattr(a,"name","Moon") print getattr(a,"name")else : pass

if hasattr(a,"age") : print getattr(a,"age")else : pass#dahlMoon50

: 2

class A(): def __init__(self, name,age) : self.name = name self.age = age def in_set(self,name,default) : self.__dict__[name] = default print self.__dict__[name]

a = A('dahl',50)

def add(x,y) : return x+y if callable(add) : add(5,6)else : pass

if callable(a.in_set) : a.in_set('age',20)else: pass

#dahlMoon5020

Namespace

__import__Import

>>>__import__('inspect')

Vars() Var(object) vars(...) vars([object]) -> dictionary Without arguments, equivalent to locals(). With an argument, equivalent to object.__dict__.

def add(x,y) : print(" vars : ",vars()) print(" locals : ", locals()) return x + y add(5,5) vars : {'y': 5, 'x': 5} locals : {'y': 5, 'x': 5}

dir,

>>>dir(B) ['__doc__', '__init__', '__module__', 'name']

Compile String compile eval()/exec() #compile(string, '', 'eval')

>>> sl = "10 * 10">>> sll =compile(sl,'','eval')>>> eval(sll) 100#compile(string, '', 'exec')

>>> sc = "print('Hello World')">>> scc = compile(sc,'','exec')>>> exec(scc)Hello World

eval : Expression Eval >>> eval("1+2")3>>>

exec : Statement Exec >>> exec('print "hello world"')hello world>>>

Run-time function Exec # code_str = '''def add(x=1,y=1) : """ add x, y """ print(" vars : ",vars()) print(" locals : ", locals())

return x + y a = add(5,5)print(a)''# code_obj = compile(code_str, '', 'exec')print(type(code_obj))# exec(code_obj)#

vars : {'y': 5, 'x': 5} locals : {'y': 5, 'x': 5}10

reload/execfilereload()reload(...) reload(module) -> module Reload the module. The module must have been successfully imported before.

reload(inspect_sor_test) : import inspect_sor_test reload

execfile()execfile(...) execfile(filename[, globals[, locals]])

execfile(xxxx.py) : filenam

Input/format/print >>>format("12345678","8.4s") # '12341234>>>print(Hello World )Hello World>>>len([1,2,3,4]) 4>>> # >"Hello World"Hello World

Format/print/input a = input(">")print(a)Input

Repr repr(...) repr(object) -> string For most object types, eval(repr(object)) == object.>>> # str . str >>> repr('123')"'123'">>> str(123)'123

>>>repr(123) '123'>>> str(123)'123'

bin/oct/hex/ord/chr/unichar base

b=bin(10) # '0b1010int(b,2) # 10

o = oct(10) # '012'int(o,8) # 10

h = hex(10) # '0xaint(h,16) # 10

ord('1') # 49chr(49) # '1unichr(49) # u'1'

abs()cmp()cmp(x, y) -> integer Return negative if xy.divmod()divmod(10,2) : Out[333]: (5, 0)divmod(11,2) : Out[334]: (5, 1)max() max([1,2,3,4]) : 4min() min([1,2,3,4]) : 1pow() pow(x, y[, z]) -> number : (x**y) % zsum()

File

Open()/file() file() file('test.txt','w') file('test.txt','a')

open()f = open(".txt", 'w') f.close()