Python Forum
Question about naming variables in class methods
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Question about naming variables in class methods
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.

Possibly Related Threads…
Thread Author Replies Views Last Post
  a function common to methods of a class Skaperen 7 391 Oct-04-2021, 07:07 PM
Last Post: Skaperen
  How to pass variables from one class to another hobbyist 18 855 Oct-01-2021, 05:54 PM
Last Post: deanhystad
  Acess variables from class samuelbachorik 3 318 Aug-20-2021, 02:55 PM
Last Post: deanhystad
  Python Style and Naming Variables rsherry8 3 624 Jun-07-2021, 09:30 PM
Last Post: deanhystad
  Listing All Methods Of Associated With A Class JoeDainton123 3 751 May-10-2021, 01:46 AM
Last Post: deanhystad
  too many methods in class - redesign idea? Phaze90 3 853 Mar-05-2021, 09:01 PM
Last Post: deanhystad
  Special Methods in Class Nikhil 3 830 Mar-04-2021, 06:25 PM
Last Post: Nikhil
  Naming the file as time and date. BettyTurnips 3 823 Jan-15-2021, 07:52 AM
Last Post: BettyTurnips
  API design question: use methods or properties? johsmi96 1 528 Oct-12-2020, 02:24 PM
Last Post: buran
  newbie question....importing a created class ridgerunnersjw 5 894 Oct-01-2020, 07:59 PM
Last Post: ridgerunnersjw

Forum Jump:

User Panel Messages

Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020