search

Home  >  Q&A  >  body text

python - 关于函数调用的问题

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

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

reply all(4)I'll reply

  • 高洛峰

    高洛峰2017-04-18 10:20:48

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

    reply
    0
  • 巴扎黑

    巴扎黑2017-04-18 10:20:48

    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.

    reply
    0
  • 天蓬老师

    天蓬老师2017-04-18 10:20:48

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

    reply
    0
  • ringa_lee

    ringa_lee2017-04-18 10:20:48

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

    reply
    0
  • Cancelreply