1.2.3python3函数

xiaoxiao2021-02-28  80

进阶函数 第三节

 

1.习题反馈

 

2.自省与函数

 func.__code__

 

 

def fun(a,b):

   return a+b

print(dir(fun.__code__))

输出为

 

['__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__','__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__','__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__','__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'co_argcount','co_cellvars', 'co_code', 'co_consts', 'co_filename', 'co_firstlineno','co_flags', 'co_freevars', 'co_kwonlyargcount', 'co_lnotab', 'co_name','co_names', 'co_nlocals', 'co_stacksize', 'co_varnames']

 

则可以通过这些数据来调用查看功能

 

比如

print(fun.__code__.co_name)

输出为函数的名字:fun

print(fun.__code__.co_varnames)

输出函数变量为:('a', 'b')

 

3.作用域问题再议

(见上次函数作用域)

 

 

4.可变参数的魔法与禁忌     

a=[1,58,2,9]

def func(arg):

   a[0]=5

   return arg

print(func(a))

输出结果为

[5, 58, 2, 9]

这样就修改了原来的变量这样是很危险的行为。导致原来的a不是原来的值。

 

咋回事?

转载请注明原文地址: https://www.6miu.com/read-82356.html

最新回复(0)