Chapter 10, Lesson 2 Text URL

Lesson Two: Class Variables and Methods


Illustration of gears working togetherNow that you understand the general theory of how objects are built, let's roll up our sleeves and get to work creating your own Python classes. In this lesson, you are going to learn how to create Python classes that have dataand methods to do useful work.

Locating Class Definitions

Just like functions, classes cannot be used by other code until they have first been defined. This means if you are putting a class in your source file, you want it to go near the top, before any other main program code attempts to use that class. Remember, a Python class starts with the class keyword, followed by the class name and a colon (:). You indent all statements that belong to the class, and the class definition ends at the first non-indented line.

class SmartPhone:
   # statements belonging to the class indented here

# other program statements go here


Defining and Accessing Class Data

The data that belongs to a class is held in variables. You may also see class data referred to as a property or attribute. To add a property to your class, simply initialize a variable inside the indented class body with an assignment statement. The example below creates three class variables, manufacturerringtone and price.

class SmartPhone:
   manufacturer = "Apple"       # initialize a class variable 
   ringtone = "Marimba"         # initialize a class variable
   price = 995.00               # initialize a class variable
# other program statements go here

To get or set the value in a class variable, write the name of the class, then a dot, and then the variable name. We've extended the example below to print the SmartPhone's manufacturer, update the ringtone and then print the new ringtone. You can use class variables just like regular variables, passing them into functions as inputs, making them part of larger expressions or using them in assignment statements.

class SmartPhone:
   manufacturer = "Apple"
   ringtone = "Marimba"
   price = 995.00
# other program statements go here
print(SmartPhone.manufacturer)        # read value of a class variable
SmartPhone.ringtone = "Crickets"      # update value of a class variable
print(SmartPhone.ringtone)            # verify updated value

Try this on your own! In the empty code box below, create a class with a name that you choose. Then, add at least one class variable with some initial value. In the main code, read the variable's value and print it to the screen. Finally, update the variable to a different value and print it again to make sure the change worked as you expected.

Try It Now


Defining and Using Class Methods (Functions)

Most classes are not very useful until you add some behavior in the form of methods (functions that belong to the class). To add a method to a class, just enter the function definition as part of the indented class body. Use the standard "def" keyword to begin and be sure to include any required input parameters inside the parentheses.

Later, when you want to call this function on the class, start with the class name, followed by a dot and the function name. The example below demonstrates adding a dial_tone() function to the SmartPhone class and then calling it from the main program code.

class SmartPhone:
   manufacturer = "Apple"
   ringtone = "Marimba"
   price = 995.00
   def dial_tone():               # define a method belonging to this class
      print("Beep, Beep, Beep")

# other program statements go here
SmartPhone.dial_tone()            # call a method belonging to a class

Here is another example where we have defined a method called identify() that prints out some basic information about the SmartPhone. Notice that the class methods may also make use of the class variables by using the class name and a dot in front. Run the code to confirm you see a nicely formatted output message with the expected data.

Try It Now

class SmartPhone:
manufacturer = "Apple"
ringtone = "Marimba"
price = 995.00
def identify():
print(str.format("I am a {} SmartPhone that costs {}",SmartPhone.manufacturer, SmartPhone.price))
# other program statements go here
#SmartPhone.dial("867-5309") # un-comment this line once you've added dial()

Can you modify this code and add a new function? Try creating a function called dial() that will accept an input parameter called phoneNumber. The method should simply print "Dialing " and the phoneNumber to the screen. Un-comment the example line that calls dial() in the example and run the code again to see your new method in action!


Summary - Class Variables and Methods

Remember the following key points when creating your class, class variables and class methods:

  1. The class definition should be near the top of your source file, before any code that uses it.
  2. The class variables should be initialized with indented statements inside the class body.
  3. The class methods should be initialized with "def", similarly indented inside the class body.
  4. To use a class variable or method, always start with the class name, followed by a dot and then the name of the variable or method.
Experienced programmers who are familiar with other languages may be wondering about creating "instances" or copies of a class. Python does allow you to create data and methods that apply individually to each unique copy of a class, and we'll explore that concept in the following chapter! The class variables and methods we have described so far are similar to "static" features in traditional OOP terms.


Work with Me: Mr. Roboto


In this exercise, you are going to create your own class that acts as a friendly robot. Here are your class requirements:

  1. The class should be named "Robot"
  2. The class should have two class variables:
    • name, initialized to "Mr. Roboto"
    • thankYou, initialized to "Domo arigato"
  3. The class should have one class method:
    • thanks(), which will print the message "<thankYou>, <name>", substituting in the class variable values.
  4. In your main program code, begin by calling Robot.thanks().
  5. Next, update the Robot's thankYou variable to "Thankee Kindly" and the name variable to "T-1000"
  6. Finally, call Robot.thanks() again to confirm your Robot now produces a message with the new phrase and name.

When you are done, your program output should look like this:

Domo arigato, Mr. Roboto
Thankee Kindly, T-1000

Try It Now




Try updating the variables with your own names and phrases - the Robot should handle them all!

Last modified: Sunday, 18 August 2019, 10:09 PM