简体   繁体   English

将变量名传递给函数?

[英]Pass variable name into function?

I have a function that contains several variables, but I only want to run it for one variable at the time. 我有一个包含多个变量的函数,但是我只想同时为一个变量运行它。 For example only for "exrate". 仅用于“ exrate”。 The idea is to pass "exrate" into the function and then for-loop "exrate" only and calculate the result. 想法是将“ exrate”传递到函数中,然后仅对“ exrate”进行循环并计算结果。 Unfortunately the the value "turnover" does not change. 不幸的是,值“营业额”没有改变。

exrate = 100
sales = 0

def sim(var, min, max):
    for var in range(min, max):
        turnover = 1000 * (exrate/100) + sales
        print(turnover)

sim(exrate, 100, 105)
sim(sales, 1000, 1100)

Let's try to refactor your original code a bit: 让我们尝试重构一下原始代码:

exrate = 100
sales = 0

def sim(var, min, max):
    for var in range(min, max):
        turnover = 1000 * (exrate/100) + sales
        print(turnover)

First, we can factor out the function used in sim, which would be: 首先,我们可以将sim中使用的函数分解为:

def f(exrate, sales):
    return 1000 * (exrate/100) + sales

and that function can be simplified further 1000/100=10 : 并且该函数可以进一步简化为1000/100 1000/100=10

def f(exrate, sales):
    return 10 * exrate + sales

You're using globals exrate=100, sales=0 but that's not a good idea, so lets' get rid of those globals by just using default parameters: 您使用的是全局变量exrate=100, sales=0但这不是一个好主意,所以让我们通过使用默认参数来摆脱这些全局变量:

def f(exrate=100, sales=0):
    return 10 * exrate + sales

Now, at this point we've got a mathy function we can use as input to another functions, it's a function with one single responsability. 现在,在这一点上,我们已经有了一个数学函数,可以将其用作另一个函数的输入,这是一个具有单一职责的函数。

So let's say we want to see how this function evolves with respect to one of its independent variables (exrate or sales) : 假设我们要了解此函数如何针对其自变量之一(exrate or sales)

for i in range(100, 1000, 100):
    print(f(exrate=i))

for i in range(0, 1000, 200):
    print(f(sales=i))

Or both: 或两者:

for i in range(0, 1000, 200):
    print(f(exrate=200, sales=i))

The main idea would be, when simulating something is a good idea to split the code into code that does the simulation (plotting the function in a graph, print values onto a console, ...) and the code which is the simulation itself (in this case, a simple linear function of the form f(x)=ax+b ) 主要思想是,在进行某些模拟时,最好将代码拆分为进行模拟的代码(在图形中绘制函数,将值打印到控制台上,...)和作为模拟本身的代码(在这种情况下,形式为f(x)=ax+b简单线性函数

You are using a variable external to the function in the definition. 您正在定义中使用函数外部的变量。 Consider replacing exrate with var within the function definition. 考虑在函数定义中用var替换exrate。

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

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