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
或许多其他方式来完成。
但是为什么这样不行呢?这种访问方式背后是否有任何 'must' 原因?它会让 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()
我只是觉得这是更本能的编写代码的方式。
也许只有我。
因为你在func1
函数中没有说return
,所以你应该这样做:
def func1():
a = [1,2,3,4,5]
return a
def func2():
b = func1()
print(b[0])
一个函数(在你的例子中是一个过程,因为它没有 return 任何东西)是对数据的处理,而不是像对象或结构这样的数据持有者。当您编写 b = func() 时,您希望获得 func() 的结果。您不必知道 func 中发生了什么。 a 在你的函数中是一个内部变量,可能在函数结束时被垃圾收集(没有人引用它)
你把 class variables
误认为是 functions variables
</p>
<pre># 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()
不过我知道这个很重复:
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
或许多其他方式来完成。
但是为什么这样不行呢?这种访问方式背后是否有任何 'must' 原因?它会让 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()
我只是觉得这是更本能的编写代码的方式。 也许只有我。
因为你在func1
函数中没有说return
,所以你应该这样做:
def func1():
a = [1,2,3,4,5]
return a
def func2():
b = func1()
print(b[0])
一个函数(在你的例子中是一个过程,因为它没有 return 任何东西)是对数据的处理,而不是像对象或结构这样的数据持有者。当您编写 b = func() 时,您希望获得 func() 的结果。您不必知道 func 中发生了什么。 a 在你的函数中是一个内部变量,可能在函数结束时被垃圾收集(没有人引用它)
你把 class variables
误认为是 functions variables
</p>
<pre># 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()