简体   繁体   English

从外部调用函数 python

[英]calling functions python from outside

I have small a python script looking something like this:我有一个小的 python 脚本,看起来像这样:

def number1():
    x = 1
    open_numbers = []
    open_numbers.append(x)
    return open_numbers

def myfunction(open_numbers):
    y = 1
    open_numbers.append(y)

I would like to call the myfunction in the the end of the script.我想在脚本末尾调用 myfunction 。 Using使用

myfunction()

But it keeps telling me missing 1 required positional argument: 'open_numbers'但它一直告诉我missing 1 required positional argument: 'open_numbers'

Tried passing the argument and got name 'open_numbers' is not defined尝试传递参数并得到name 'open_numbers' is not defined

I plan to add more functions later and run them the same way我计划稍后添加更多功能并以相同的方式运行它们

function(arg)
function2(arg)
function3(arg)

Solution解决方案

First of all, your code was not properly indented.首先,您的代码没有正确缩进。 I have corrected that.我已经纠正了。
The function myfunction takes in a list ( open_numbers ) as input and should return it as well. myfunction接受一个listopen_numbers )作为输入,也应该返回它。

I have passed in the output of number1() as the input to myfunction() .我已经传入number1()的 output 作为myfunction()的输入。 This should create a list: [1, 1] .这应该创建一个列表: [1, 1] And that's what it did.这就是它所做的。

def number1():
    x = 1
    open_numbers = []
    open_numbers.append(x)
    return open_numbers


def myfunction(open_numbers):
    y = 1
    open_numbers.append(y)
    return open_numbers

myfunction(number1())

Output : Output

[1, 1]

you need to pass in an object to your function.您需要将 object 传递给您的 function。 you can call your function with an empty list if you want:如果需要,您可以使用空列表调用 function:

a = []
myfunction(a)

You might want to define default parameter, and return the updated value您可能想要定义默认参数,并返回更新后的值

def myfunction(open_numbers = []):
    y = 1
    open_numbers.append(y)
    return open_numbers

Then you can call it with passing parameter myfunction([1]) or without myfunction()然后您可以使用传递参数myfunction([1])或不myfunction()来调用它

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

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