Skip to content Skip to sidebar Skip to footer

Python Keyword Arguments In Class Methods

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:

Solution 1:

defgamesplayed(self, team = None, startyear = self._firstseason, endyear = self._lastseason):

In the function declaration you are trying to reference instance variables using self. This however does not work as self is just a variable name for the first argument of the function which gets a reference to the current instance passed in. As such, self is especially not a keyword that always points to the current instance (unlike this in 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.

Solution 2:

Default values for keyword arguments are bound at module construction time, not at class instance construction time. This is why self is not defined in this context.

The same fact about default values can create all sorts of problems any time you want a keyword argument where the default value updates every time the function is called. When you run the program, you'll find that the default value you expect to be updating is always set to the value constructed when the module was first initialized.

I would advise using None as a default keyword parameter in both instances, as poke and others have suggested. Your code could look something like:

defgamesplayed(self, team=None, startyear=None, endyear=None):
    ifnot startyear:
        startyear = self._firstseason
    ifnot endyear:
        endyear = self._lastseason

Post a Comment for "Python Keyword Arguments In Class Methods"