3

给Python中的函数换脑

 2 years ago
source link: https://www.lujun9972.win/blog/2019/09/13/%E7%BB%99python%E4%B8%AD%E7%9A%84%E5%87%BD%E6%95%B0%E6%8D%A2%E8%84%91/index.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

给Python中的函数换脑

https://lerner.co.il/2017/02/02/python-function-brain-transplants/ 上看到的,颇为有趣,记录一下。

python中函数对象有一个 __code__ 属性(它也是一个code对象)保存了函数定义中的实际代码。 通过它可以获取到一些该函数的元信息,比如 __code__.co_argcount 可以查看函数参数个数, __code__.co_code 可以查看函数的字节码。

虽然 __code__ 本身是一个只读对象,但是 function对象本身是可以修改的,所以如果我们可以将它的 .__code__ 属性替换掉。比如

def foo():
    return "foo"

def bar():
    return "bar"

# 开始换脑
bar.__code__ = foo.__code__
return bar()
foo


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK