Methods

Before showing how instance variables ought to be created, let's take a look at how we can add operations to a class. suppose, for example, that we want to calculate the lightness of a color, that is, how close it is to being pure white. By definition, a color's lightness is the average of its strongest and weakest RGB values scaled to lie between 0 and 1. As a function, this is as follows:

Download oop/color_lightness_func.py

def lightness(color):

strongest = max(color.red, color.green, color.blue) weakest = min(color.red, color.green, color.blue) return 0.5 * (strongest + weakest) / 255

If we want to make the calculation a method of the class Color, we simply move its definition into the class.

>>> purple = Color() >>> purple.lightness

Color red green blue

Runtime stack after calling purple.lightness()

Color red green blue

Runtime stack after calling purple.lightness()

Figure 13.1: Automatic self

Download oop/color_lightness_method.py

class Color(object):

'''An RGB color, with red, green and blue components.'''

def lightness(self):

'''Calculate the lightness of this color.'''

strongest = max(self.red, self.green, self.blue) weakest = min(self.red, self.green, self.blue) return 0.5 * (strongest + weakest) / 255

Actually, we do one other thing as well. We take out the parameter color and replace it with one called self. Whenever Python called a method for an object, it automatically passes a reference to that object as the method's first argument (see Figure 13.1). This means that when we call lightness, we don't need to give it any arguments—Python supplies the object itself for us. Inside the method, we can then access the object's instance variables using the usual dot notation on that variable:

Download oop/color_lightness_call.cmd

>>> purple = Color() >>> purple.red = 255 >>> purple.green = 0 >>> purple.blue = 255 >>> purple.lightness() 0.5

The rule about self means that when you define a method, you must include one more parameter than you're actually going to pass in. Alternatively, when you call a method, you provide one less parameter than the method's definition seems to require. Forgetting this is a very common beginner's mistake. Forgetting to put self in front of something that you intended to be a member variable is another common beginner's mistake.

For example, if the class was defined this way:

Download oop/broken_color_self.py

class Color(object):

'''An RGB color, with red, green and blue components.'''

def lightness(self):

'''Return the lightness of this color.'''

# Fails: no such variables 'red', 'green', and 'blue' strongest = max(red, green, blue) weakest = min(red, green, blue) return 0.5 * (strongest + weakest) / 255

then purple.lightness() would produce an error, because the variables red, green, and blue don't exist in lightness, even though purple.red, pur-ple.green, and purple.blue have been assigned values.

Was this article helpful?

0 0

Post a comment