简体   繁体   English

在python中调用函数时替换函数的变量?

[英]Replace variable of a function while calling it in python?

Sorry for my bad english.对不起,我的英语不好。

Is there any way to replace variable of a method from outside?有没有办法从外部替换方法的变量?

Suppose i have two files app.py and try.py.假设我有两个文件 app.py 和 try.py。

In app -在应用程序中 -

def call():
  c=5
  return c

In try -在尝试 -

from app import *
c=1000
d=call()
print(d)

When i run try, here i want the output to be 1000 not 6. Is there any way to do this ?当我运行 try 时,我希望输出为 1000 而不是 6。有什么办法可以做到这一点?

I don't know any way to change c dynamically.我不知道动态更改c任何方法。 Python compiles c = 5 into a LOAD_CONST op code as seen in the disassembly. Python 将c = 5编译为 LOAD_CONST 操作代码,如反汇编中所示。 And changing that op code would require, um, .... I don't know.更改该操作代码需要,嗯,.... 我不知道。

>>> from dis import dis
>>> def call():
...   c=5
...   return c
... 
>>> dis(call)
  2           0 LOAD_CONST               1 (5)
              2 STORE_FAST               0 (c)

  3           4 LOAD_FAST                0 (c)
              6 RETURN_VALUE

You can monkey patch, though.不过,你可以猴子补丁。 Write your own implemenation of call and assign it dynamically at the start of your program.编写您自己的call实现并在程序开始时动态分配它。

import app

# from app, a reimplementation of call
def my_app_call_impl(c=1000):
    return c

app.call = my_app_call_impl

add c argument to the function and use it like that向函数添加 c 参数并像这样使用它
app file应用程序文件

def call(c):
    return c

The second file第二个文件

from app import *
c = 1000
d = call(c)
print(d)

if you want to c have a default value then app file should look like this如果你想让 c 有一个默认值,那么 app 文件应该是这样的

def call(c = 5):


You can define parameters for the call function:您可以为调用函数定义参数:

app.py:应用程序.py:

def call(c): # one parameter, c
    return c

try.py尝试.py

from app import *
c = 1000
d = call(c) # function called with c as an argument

print(d) # 1000

You can also use 5 as a default:您还可以使用 5 作为默认值:

app.py应用程序

def call(c = 5):
    return c

try.py尝试.py

from app import *

d = call()
print(d) # 5

Functions in Python Python 中的函数

*in app.py : * *在 app.py 中:*

def call(c=5):
    return c

*in try.py : * *在try.py中:*

from app import *
d=call(1000)
print(d)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM