Help Defining Global Names

后端 未结 6 451
情深已故
情深已故 2021-01-25 22:48

My Code:

def A():
    a = \'A\'

    print a

    return

def B():

    print a + \' in B\'

    return

When B() is entered into the interpeter

6条回答
  •  北荒
    北荒 (楼主)
    2021-01-25 23:34

    i'm pretty new to Python and you might want to take thes following with a grain of salt, but did you consider to have your variable a and the functions A() and B() as members of a class?

    class myClass(object):
    
        def __init__(self):
            self.a = ''
    
        def A(self):
            self.a = 'A'
            print self.a
    
        def B(self):
            print self.a + ' in B'
    
    
    def main():
        stuff = myClass()
        stuff.A()
        stuff.B()
    
    if __name__ == '__main__':
        main()
    

    When i save the code above in a file and run it, it seems to work as expected.

提交回复
热议问题