python-function-code

>>> def f_1():
    print("I am f_1")

>>> def f_2():
    print("I am f_2")

    
>>> f1 = f_1
>>> f2 = f_2
>>> f1.__code__
<code object f_1 at 0x00FFB840, file "<pyshell#31>", line 1>
>>> f2.__code__
<code object f_2 at 0x01028610, file "<pyshell#34>", line 1>
>>> f2.__code__,f1.__code__ = f1.__code__,f2.__code__
>>> f1
<function f_1 at 0x00FFD7C8>
>>> f1()
I am f_2
>>> f2
<function f_2 at 0x01089150>
>>> f2()
I am f_1

>>> f2,f1 = f1,f2
>>> f1()
I am f_1
>>> f2()
I am f_2

f2,f1 = f1,f2 <=> f2.__code__,f1.__code__ = f1.__code__ ,f2.__code__

>>> def f_1():
    name = "f_1"
    print(name)

    
>>> def f_2():
    xxx = "f_2"
    print(xxx)

>>> f1 = f_1
>>> f2 = f_2
>>> f1()
f_1
>>> f2()
f_2
\
>>> f1,f2 = f2,f1
>>> f1()
f_2
>>> f2()
f_1
>>> f1,f2 = f2,f1
>>> f1.__code__,f2.__code__ = f2.__code__,f1.__code__
>>> f1()
f_2
>>> f2()
f_1
>>> 

看来,__code__对象包含了函数对象的局部变量。

2.__dict__属性

The namespace supporting arbitrary function attributes.Writable
 f1.__dict__
{}
>>> def f_3():
    print("I am f_3")

    
>>> f1.__dict__['f_3'] = f_3
>>> f1.f_3()
I am f_3

 所谓的fucntion attributes指的是什么,应该是所有的对象吧,不太清楚。

>>> class C:
    def __init__(self):
        name = "a instance of class C"
        print(name)

        
>>> f1.__dict__['classC'] = C
>>> a = f1.classC()
a instance of class C
>>> f1.classC.__qualname__
'C'
>>> myName = "Lworld"
>>> f1.__dict__['name'] = myName
>>> f1.name
'Lworld'

  >>> a = range(10)
>>> f1.__dict__['Iter'] = a
>>> f1.Iter
range(0, 10)
>>> for item in f1.Iter:
print(item)

 
  


0
1
2
3
4
5
6
7
8
9

 

 

转载于:https://www.cnblogs.com/darknife/p/3148949.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值