Python Forum

Full Version: Question about naming variables in class methods
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi there, in the following code I have a class method called addFormattedCosts. I get that when working with instance variables you use the "self" keyword according to convention. In the below function I didn't use the self before the variables within the method and didn't get an error. The variables used in the method are like "helper" variables and nothing interacts with any actual instance variables which Is why I think I don't get errors. But what affect will occur by not putting the ".self" before these "helper" variables. Should I and why?

def addFormattedCosts(self, costList):
	millionFormat = (float(cost.replace('M', '')) * 1000000 if "M" in cost else 0.0 for cost in costList)
	thousandFormat = (float(cost.replace('K', '')) * 1000 if "K" in cost else 0.0 for cost in costList)
	finalSum = sum(millionFormat) + sum(thousandFormat)
	return int(finalSum)
If they're meant to just be used in that method (that is, they're local variables), then you shouldn't use self. By "class method" do you mean decorated with @classmethod? I'm going to guess (and you can check whether this is correct for yourself) that if you do use self there, you'll be creating class variables that are accessible to all class and instance methods. You should make variables as tightly scoped as possible (so as above, not using self if you don't need to). Note also, that the convention is to call the first parameter to a class method cls, rather than self.

FWIW, your thread title is a bit misleading - there's nothing really about naming here.