I’m attempting to write a class method that takes 3 keyword arguments. I’ve used keyword arguments before but can’t seem to get it to work inside of my class. The following code:
def gamesplayed(self, team = None, startyear = self._firstseason,
endyear = self._lastseason):
totalGames = 0
for i in self._seasons:
if((i.getTeam() == team or team == "null") and
i.getYear() >= startyear and i.getYear() <= endyear):
totalGames += i .getGames()
return totalGames
produces the error:
NameError: name ‘self’ is not defined
If I take out the keyword arguments and make them simple positional ones, it works fine. Therefore I am not sure where my problems lies. Thanks in advance for any help.
In the function declaration you are trying to reference instance variables using
self. This however does not work asselfis just a variable name for the first argument of the function which gets a reference to the current instance passed in. As such,selfis especially not a keyword that always points to the current instance (unlikethisin other languages). This also means that the variable is not yet defined during the declaration of the function.What you should do is to simply preset those parameters with
None, and preset them to those values in that case inside the function body. This also allows users to actually parse a value to the method that results in the default values without having to actually access the values from somewhere inside your class.