简体   繁体   中英

Is there a way to create a function that will run this code but without passing so many arguments?

I am trying to make code from my project more efficient, shorter but not hard to read/understand.

I see that there are some actions that repeat themselves a couple of times in the code. It is a game so it is required to repeat those. I thought that maybe I should create a function to call every time instead, but it does not seem friendly to read, because, following a condition, I need to change a couple of variables so I need to pass all of them to the function.

Here is an example:

if nxtTurn == 'player1':
    card2, player1 = EgyptionWarHelper.pull_out_card(player1, nxtTurn)
    storage.append(card2)
    nxtTurn = 'player2'
else:
    card2, player2 = EgyptionWarHelper.pull_out_card(player2, nxtTurn)
    storage.append(card2)
    nxtTurn = 'player1'

I wanted to create a function that does this, but then realized I will need to pass all of the variables to it and then return a tuple of 2 variables at the end of it. I did hear about global variables but I never really used them and I don't know if they are the solution for this.

EDIT: I found out that I didn't have to pass some of the argument so after I edit the function and used temporary variables as well, the code is much more readable.

Additionally, as commented, I didn't have to return player and player2 because python passes lists by reference and not by value.

why not using a temporary variable ?

 if nxtTurn == 'player1': player = player1 nxtTurn = 'player2' else: player = player2 nxtTurn = 'player1' card2, player1 = EgyptionWarHelper.pull_out_card(player, nxtTurn) storage.append(card2)

it's easily readable and maintainable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM