问题描述:

I have a function:

def create_discs(noDiscs):

which when called creates a specified number of discs, so for example:

create_discs(5)

will create 5 discs.

I then want to use the integer inputted into the create_discs function in a separate function:

def hanoi(disc_int):

In other words I would like disc_int to equal 5 (or whatever number is inputted)

Can anyone help me?

网友答案:

If you want two functions to share state like this, they should be defined as methods of a class.

class Hanoi(object):

    def __init__(self, num_discs):
        self.num_discs = num_discs

    def create_discs(self):
        # use value of self.num_discs

    def hanoi(self):
        # use value of self.num_discs

h = Hanoi(5)
h.create_discs()
h.hanoi()
网友答案:

If you're passing 5 to create_discs, can you do:

num = 5

create_discs(num)
hanoi(num)
网友答案:

You could make a closure:

def create_discs(num):
    # create some discs
    def hanoi_closure():
        # now num is available within this function
        # do hanoi stuff
        return
    return hanoi_closure

hanoi = create_discs(5)
hanoi()

In this case, create_discs defined your hanoi function within itself so that num was within its scope (automatically, no need to store anything in a global or a class!) and it returned the inner function so you could call it later.

If create_discs was already supposed to return something, then you could just return a tuple with what it was returning plus the inner function:

def create_discs(num):
    # ...
    return what_it_normally_returns, hanoi_closure

create_discs_result, hanoi = create_discs(5)
hanoi()
相关阅读:
Top