Python Programming for Raspberry Pi, Sams Teach Yourself in 24 Hours

(singke) #1

attribute.


As with setters, it’s somewhat of a standard convention to name getter accessor methods starting with
get_, followed by the attribute name, as shown here:


Click here to view code image


def get_description(self):
return self.__description

This is all there is to it! Accessor methods aren’t overly complicated; they just return the current
value of the attribute. Notice that even though no data is passed to the accessor method, you still need
to include the self keyword as a parameter. Python uses this keyword internally to reference the
class instance.


When you create your classes, you need to create one setter and one getter for each attribute you use
in your class. Listing 14.1 shows the script1401.py program, which demonstrates creating setter and
getter methods for the Product class attributes and then using them in a program.


LISTING 14.1 Using Setter and Getter Methods


Click here to view code image


1: #!/usr/bin/python3
2:
3: class Product:
4: def set_description(self, desc):
5: self.__description = desc
6:
7: def get_description(self):
8: return self.__description
9: def set_price(self, price):
10: self.__price = price
11:
12: def get_price(self):
13: return self.__price
14:
15: def set_inventory(self, inventory):
16: self.__inventory = inventory
17:
18: def get_inventory(self):
19: return self.__inventory
20:
21: prod1 = Product()
22: prod1.set_description('carrot')
23: prod1.set_price(1.00)
24: prod1.set_inventory(10)
25: print('{0} - price: ${1:.2f}, inventory: {2:d}'.format(
prod1.get_description(),prod1.get_price(), prod1.get_inventory()))

After you instantiate an instance of the Product class (line 21), you need to use the setter methods
to set the initial values (lines 22 through 24). To retrieve the attribute values (as in the print()
statement in line 25), you just use the get_ methods for each attribute.


When you run the script1401.py program, you should see this output from the instance values:


Click here to view code image

Free download pdf