简体   繁体   English

关于将变量分配给 function 的基本问题

[英]basic question about assigning a variable to a function

Let's say i want to import and use a function func1 from a module func.py as a variable f.假设我想从模块 func.py 导入并使用 function func1 作为变量 f。 I would like to use a short name f so that i don't have to write func.func1 everytime i use it.我想使用一个短名称 f 这样我就不必每次使用它时都写 func.func1 。

The module func.py is模块 func.py 是

    def func1(n):
        print(n+1)

and i want to import func我想导入 func

    import func
    f = func.func1()

Why does it show error in () as "func1 missing 1 required positional argument n"?为什么它在()中显示错误为“func1缺少1个所需的位置参数n”?

    import func
    f = func.func1

while this doesn't show error?虽然这没有显示错误?

what is the difference between func.func1 and func.func1()? func.func1 和 func.func1() 有什么区别?

When you do f = func.func1() , you are attempting to call func1 , and bind its return value to f .当您执行f = func.func1()时,您正在尝试调用func1并将其返回值绑定到f That's not what you intend, and it doesn't work since func1 expects to be given an argument when it is called.这不是您想要的,并且它不起作用,因为func1期望在调用它时给出一个参数。 But when you put the () on the end, Python sees you making a function call.但是,当您将()放在末尾时,Python 会看到您进行 function 调用。

When you leave off the () , there's no call being done, you're just binding the function to a new name.当您离开()时,不会进行任何调用,您只是将 function 绑定到一个新名称。 As has been mentioned in the comments, you can do this in the same step as your import statement, with from func import func1 as f .正如评论中提到的,您可以在与 import 语句相同的步骤中执行此操作,使用from func import func1 as f

This is a quick answer.这是一个快速的答案。 When you do f = func.func1() you need to pass a variable into the func1(var).当您执行 f = func.func1() 时,您需要将一个变量传递给 func1(var)。 In your module it contains a variable called n.在您的模块中,它包含一个名为 n 的变量。 N is used to be added to one correct? N是用来加一的吗? So when you call the module you also need to give it n or any other variable but make sure its an int.因此,当您调用模块时,您还需要给它 n 或任何其他变量,但要确保它是一个 int。 :

n = 10
f = func.func1(n)

Now it should work fine.现在它应该可以正常工作了。 All you have to do Is pass a variable inside the parrenthases and it should work.您所要做的就是在括号内传递一个变量,它应该可以工作。

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

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