python - 关于函数调用的问题
天蓬老师
天蓬老师 2017-04-18 10:18:48
0
4
698
def test1():
    a = 1
    b = 2
    
def test2():
    c = 3
    d = c + a
    print(d)
test2

这边想实现下面的test2调用上面test1里面的数据,要怎么实现,使用的是python3
天蓬老师
天蓬老师

欢迎选择我的课程,让我们一起见证您的进步~~

reply all(4)
小葫芦

First of all, your demand is impossible and unreasonable. It is impossible for two separate functions to access the variables inside each other

You can do it if you use closures, but I don’t know if that’s what you want:

def test1():
    a = 1
    b = 2
    def test2():
        c = 3
        d = c + a
        print(d)
    return test2

test2 = test1()

test2()
巴扎黑

You can encapsulate test1 into a class

#-*-coding:utf8-*-
class test1():
    """docstring for test1"""
    def __init__(self):
        self.a=0
        self.b=0
        self.test1()
    def test1(self):
        self.a=1
        self.b=2
test = test1()
def test2():
    c=3
    d=c+test.a
    print (d)
test2()

Initialization can be placed where you want to call it, and the test1() method is called by default during initialization, so that the data can be accessed through the class object.

Peter_Zhu

You can let test1 use return to return the values ​​​​of a and b:

def test1():
    a = 1
    b = 2
    return a,b

def test2():
    c = 3
    a,b = test1()
    d = c + a
    print(d)
test2()
左手右手慢动作

Haha, they are all talents, closure, class sealing, clear return, each of the above is an independent solution.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template