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

 

 

posted @ 2013-06-21 20:25  youJumpILook  阅读(419)  评论(0编辑  收藏  举报