What to name a variable when the name you want is already taken
With a function like this:
def example(things):
x1 = 1
x2 = 1
for thing in things:
(x2, y2) = some_function(thing)
x1 += x2
y1 += y2
return (x1, y1)
The problem that comes up is that x1
and x2
represent the same thing, and so do y1
and y2
. Assuming you know nothing about x1
and y1
, is there any rule of thumb for what to name x2
and y2
in this case?
In a simpler case (one variable), I would just do x += some_function(in)
, but Python won't let me do (x, y) += recursive(in)
, so I have to have these. I suspect the name isn't particularly i开发者_开发技巧mportant, but it bothers me using bad variable names.
In today's case, the variables were ways
and calls
and I just appended r
on the front of each:
def make_change(amount, coins):
# -- stuff -- #
if len(coins) > 1:
(rways, rcalls) = make_change(amount, coins[1:])
ways += rways
calls += rcalls
return (ways, calls)
When you have two variables that have similar content, give them names that express what is similar and also what is different. I have no idea what you're talking about with "ways" and "calls", but it appears that what you're doing is you have a total and a, what, transaction amount? In that case, I'd call them "ways_total" and "ways_tx" or something like that.
What I would definitely encourage you to NOT do is just tack a "1" and a "2" on the end, or deliberately misspell one.
Just the other day I was looking at a program that calculates freight costs, and I found three variables named "freight", "freightcost", and "freightt" (the final "t" doubled). This gave me no clue what the difference between the three was. I had to dig through the program to figure it out.
I've seen plenty of programs that "solve" the same problem by calling them freight1 and freight2.
If you need two variables, there must be SOME difference between them, and when you're writing the code, you must know what that difference is. Give the reader a clue.
In this particular case I'd name your ways
and calls
as total_ways
and total_calls
and would have the local ones with 'r' just without 'r'. I think such naming would be a bit more descriptive for someone else reading this code.
You could create a custom result object that contains the information you want to keep track of and defines an __add__()
method so that they can be added.
def make_change(amount, coins):
class Tally(object):
def __init__(self, ways=0, coins=0):
self.ways, self.coins = ways, coins
def __add__(self, other):
return Tally(self.ways + other.ways, self.coins + other.coins)
tally = Tally()
# -- stuff, presumably updating tally.ways and tally.coins -- #
if len(coins) > 1:
tally += make_change(amount, coins[1:])
return tally
This seems like rather a lot of work to go to, but it does express the intent more clearly.
精彩评论