简体   繁体   English

Python 函数从另一个函数调用变量。 但为什么?

[英]Python function calling a variable from another function. But why?

I know this one is pretty duplicated however:但是,我知道这个非常重复:

def func1():
    a = [1,2,3,4,5]
    return a

def func2():
    b = func1()
    print(b.a[0])

func2()

AttributeError: 'list' object has no attribute 'a'

I WANT TO use '.'我想使用'.' dot function(syntax) to access variables declared in other functions like :点函数(语法)来访问在其他函数中声明的变量,例如:

print(b.a[0])
or
print(b.a)

should print out:应该打印出来:

1
or
[1,2,3,4,5]

Wouldn't it make things so much easier?它不会让事情变得更容易吗?

And I know this can be done by using class or many other ways too.而且我知道这也可以通过使用class或许多其他方式来完成。

But why won't it work this way?但是为什么它不能这样工作呢? Are there any 'must' reason(s) behind this way of access?这种访问方式背后是否有任何“必须”的原因? Will it make Python vulnerable?它会让 Python 变得脆弱吗? or will it make python unstable?还是会使python不稳定?

I wasn't able to find a perfect, concise, clear, accurate explanation for this accessing issue.我无法为这个访问问题找到完美、简洁、清晰、准确的解释。

Many Thanks.非常感谢。


to be more accurate for @Goyo对@Goyo 来说更准确

def func():
    a = [1,2,3,4,5]

def func2():
    b = func()
    b.a[0] = "Not Working"
    print(b)

func2()

or或者

def func3():
    from . import func
    b = func()
    b.a[0] = 'Not working either'
    print(b)

func3()

I just feel it is more instinctive way of writing codes.我只是觉得这是编写代码的更本能的方式。 Maybe it is just me.也许这只是我。

You are mistaking class variables with functions variables您将class variables误认为functions variables

# This a Class
class MyFunctions():
    def __init__(self):
        pass
    # This is a function of the class
    def func1():
        a = [1, 2, 3, 4, 5]
        return a

# This is a Procedure, it is not function because it returns Nothing or None
def func2():

    b = MyFunctions.func1()
    print(b[0])

    # a variable of the class
    MyFunctions.func1.a = 3
    f = MyFunctions.func1.a
    print(f)

func2()

It's because you didn't say return in the func1 function, so you should do:那是因为你没有在func1函数中说return ,所以你应该这样做:

def func1():
    a = [1,2,3,4,5]
    return a

def func2():
    b = func1()
    print(b[0])

A function (in your case a procedure since it does not return anything) is a treatment on data, not a data holder like an object or a structure.函数(在您的情况下是一个过程,因为它不返回任何内容)是对数据的处理,而不是像对象或结构这样的数据持有者。 When you write b = func() you expect to get the result of func().当您编写 b = func() 时,您希望得到 func() 的结果。 You don't have to know what happens in func.您不必知道 func 中发生了什么。 a in your function is an internal variable that might be garbage collected at the end of the function (no one referencing it)你的函数中的 a 是一个内部变量,它可能在函数结束时被垃圾收集(没有人引用它)

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

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