繁体   English   中英

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

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

但是,我知道这个非常重复:

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'

我想使用'.' 点函数(语法)来访问在其他函数中声明的变量,例如:

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

应该打印出来:

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

它不会让事情变得更容易吗?

而且我知道这也可以通过使用class或许多其他方式来完成。

但是为什么它不能这样工作呢? 这种访问方式背后是否有任何“必须”的原因? 它会让 Python 变得脆弱吗? 还是会使python不稳定?

我无法为这个访问问题找到完美、简洁、清晰、准确的解释。

非常感谢。


对@Goyo 来说更准确

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

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

func2()

或者

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

func3()

我只是觉得这是编写代码的更本能的方式。 也许这只是我。

您将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()

那是因为你没有在func1函数中说return ,所以你应该这样做:

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

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

函数(在您的情况下是一个过程,因为它不返回任何内容)是对数据的处理,而不是像对象或结构这样的数据持有者。 当您编写 b = func() 时,您希望得到 func() 的结果。 您不必知道 func 中发生了什么。 你的函数中的 a 是一个内部变量,它可能在函数结束时被垃圾收集(没有人引用它)

暂无
暂无

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

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