【问题标题】:Replace variable of a function while calling it in python?在python中调用函数时替换函数的变量?
【发布时间】:2021-09-26 01:54:24
【问题描述】:

对不起,我的英语不好。

有没有办法从外部替换方法的变量?

假设我有两个文件 app.py 和 try.py。

应用内 -

def call():
  c=5
  return c

尝试中-

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

当我运行 try 时,我希望输出为 1000 而不是 6。有什么办法吗?

【问题讨论】:

  • app 中删除c=5
  • 是否有理由需要更改值而不是重写函数以将c 作为参数传递。
  • 对了,那么c就变成了全局变量。但是,过度使用全局变量通常不是好的编程习惯,因为它会导致函数意外地改变行为。像这样的代码意味着是时候考虑创建一个类,以便对象可以包含自己的状态。
  • def call(what_to_return): return what_to_return - call(1000) - 但是你想做的事情没有真正的意义 - 你为什么要返回你传入的内容 - 为什么要传入?

标签: python python-3.x unit-testing variables methods


【解决方案1】:

我不知道有什么方法可以动态更改c。 Python 将c = 5 编译为 LOAD_CONST 操作码,如反汇编所示。并且更改该操作码需要,嗯,....我不知道。

>>> 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

不过,您可以使用猴子补丁。编写您自己的 call 实现并在程序开始时动态分配它。

import app

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

app.call = my_app_call_impl

【讨论】:

    【解决方案2】:

    将 c 参数添加到函数并像这样使用它
    应用文件

    def call(c):
        return c
    

    第二个文件

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

    如果你想让 c 有一个默认值,那么 app 文件应该是这样的

    def call(c = 5):
    
    
    

    【讨论】:

      【解决方案3】:

      你可以为调用函数定义参数:

      app.py:

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

      try.py

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

      您也可以使用 5 作为默认值:

      app.py

      def call(c = 5):
          return c
      

      try.py

      from app import *
      
      d = call()
      print(d) # 5
      

      Functions in Python

      【讨论】:

        【解决方案4】:

        *在 app.py 中:*

        def call(c=5):
            return c
        

        *在 try.py 中:*

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-09-11
          • 1970-01-01
          • 2017-03-06
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-10-25
          相关资源
          最近更新 更多