gpt4 book ai didi

python - 访问对象时运行 python 命令

转载 作者:太空宇宙 更新时间:2023-11-04 00:18:50 25 4
gpt4 key购买 nike

我有以下命令:

a = imp.load_source("a", r"some_path\some_source.py")

因此 a 是一个模块对象,我可以从中访问和运行 some_source.py 中的所有函数。在 python 中有没有一种方法可以在使用任何 some_source 函数之前运行附加功能,但不更改 some_source.py 对于例如,如果 some_source.py 具有函数 foo1foo2 ... foo100,那么我想要命令

a.foo5() 

实际执行:

imp.reload(a)
a.foo(5)

这应该应用于所有 100 个 foo 函数。

明确一点,我希望通过运行与我团队中每个人都习惯的命令相同的命令来简单地实现添加的功能 -a.foo5()。我不希望他们必须创建某种类或调用不同于他们习惯的方法。

最佳答案

你可以尝试像这样装饰你的模块:

class ReloadingModule:
def __init__(self, module):
self.module = module

def __getattr__(self, attr):
print("reloading {}...".format(self.module.__name__))
imp.reload(self.module)
return getattr(self.module, attr)


import this
this = ReloadingModule(this)

print('\n\n',this.c, '\n\n')
print('\n\n',this.s, '\n\n')

输出:

reloading this...
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
[...]


97


reloading this...
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
[...]

Gur Mra bs Clguba, ol Gvz Crgref

Ornhgvshy vf orggre guna htyl.
Rkcyvpvg vf orggre guna vzcyvpvg.
Fvzcyr vf orggre guna pbzcyrk.
[...]

用一些数学:

import math
math = ReloadingModule(math)

print(math.pi)
print(math.sin(math.pi/2))

输出:

reloading math...
3.141592653589793
reloading math...
reloading math...
1.0

关于python - 访问对象时运行 python 命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49895190/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com