Python定义函数参数传递 [英] Python definition function parameter passing

查看:79
本文介绍了Python定义函数参数传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于你们大多数人来说,这可能是常识,但是我发现很难,很难解决这个问题.如果您创建诸如

For most of you this is probably common sense but I am finding it very, very hard to get a handle on this. If you create a function such as

def one():
    x=1
    y=2
    z=3
    h=33
    j=454
    l=353
    m=898

然后可以说我还有另一个函数def two():,并且我想在def two中使用def one()中的变量,并且还要在def two()中创建两个新变量.我将如何去做.

then lets say I have another function, def two():, and I want to use the variables in def one() into def two, and I also create two new variables in def two(). How would I go about doing that.

然后,假设我有第三个函数def three(),如何将def 1和def 2中的变量使用到def 3中?我使用的方法效率非常低,可能执行的工作超出了要求.我要做的是在def 2中,将def one中的所有变量添加到def two的参数中,然后在函数2的def中也调用函数1.我知道在SO上有很多线程,我已经看过了通过他们中的许多人,他们不只是简单地.他们使用了我不熟悉的非常具体和高级的代码,因此无法理解.我的示例非常简单明了,我敢肯定,如果得到回答,它将对许多新手有所帮助.谢谢!

Then, lets say that I have a third function def three(), how would I use the variables in def 1 and def 2 into def 3? The methods I am using are very very inefficient and probably doing more than is required. What I do is in def two, a add all the variables from def one into def two's parameters, and then I also call function one in the def of function 2. I know there are numerous threads on this on SO, and I have looked through many of them and they don't simply it. They use very specific and advanced code that I am unfamiliar with and therefore don't understand. My example is very straightforward and simple and I'm sure if answered it will help many newcomers.Thanks!

我不希望以简单"的方式最终使用我不熟悉的高级代码.我想要一种简单易懂的有效"方法.

I don't want a "simple" way that ends up using advanced code I am not familiar with. I want an "efficient" method that is simple to understand.

推荐答案

如果我了解您的需求,那么我认为python带给您的最简单方法是->

If I understand what do you need then I think simplest way that python brings you is next ->

class Helper:pass 

# use name space
def one(a):  
    a.x=1
    a.y=2
    a.z=3
    a.h=33
    a.j=454
    a.l=353
    a.m=898

def two(a):
    a.y=7

a=Helper()

one(a)
print(a.x,a.y)
two(a)
print(a.x,a.y)

#-------------------------------------------------------------------
# I think you have solution and dont need to read next lines :)
# next lines are just bonus ;)
#-------------------------------------------------------------------

# you could use more independent "namespaces"
b=Helper()
one(b)
print(b.y)
print(a.y)  # "namespace a" is unchanged

# if you like to see which attributes are defined you could use funciton dir
# (under python3 it is a little more complicated)
print(dir(a))
print(dir(b))

# please dont do next lines at home!!! :P:P:P (__builtins__ is special you could get unwanted results!) 
one(__builtins__)

print(x) # 

这篇关于Python定义函数参数传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆