IntroductionClasses are the cornerstone of Object Oriented Programming. They are the blueprints used to create objects. And, as the name suggests, all of Object Oriented Programming centers around the use of objects to build programs.
You don't write objects, not really. They are created, or instantiated, in a program using a class as their basis. So, you design objects by writing classes. That means that the most important part of understanding Object Oriented Programming is understanding what classes are and how they work.
Real World ExamplesThis next part if going to get abstract. You can think of objects in programming just like objects in the real world. Classes are then the way you would describe those objects and the plans for what they can do.
Start off by thinking about a car. Car is a fairly general term, but there are some universal concepts that you can apply to just about any car. They all have four wheels, a motor, transmission, doors, a steering wheel, etc. Additionally, they all have a make and model. Couldn't each of those pieces of information be stored in a variable to describe a specific car?
What about what they can do? Nearly every car can do the same basic things, but they just might do them differently or at different speeds. You could then describe the actions that a car can perform using functions. In Object Oriented Programming, though, functions are called methods.
So, if you were looking to use "car" objects in your program, you would create a "car" class to serve as a blueprint with all of the variables that you would want to hold information about your "car" objects and all of the methods to describe what you would like your cars to be able to do.
A Python ClassNow that you have a general idea of what a class is, it's best to take a look at a real Python class and study how it is structured.
class Car(object): make = 'Ford' model = 'Pinto' year = '1971' mileage = 253812 engine = '4 cylinder' transmission = 'manual' horsepower = 100 color = 'orange' def move_forward(self, speed): print("Moving forward at %s" % speed) def move_backward(self, speed): print("Moving backward at %s" % speed)Creating a class looks a lot like creating a function. Instead of
defyou use the keyword,
class. Then, you give it a name, just like you would a function. It also has parenthesis like a function, but they don't work the way you think. For a class the parenthesis allow it to extend an existing class. Don't worry about this right now, just understand that you have to put
objectthere because it's the base of all other classes.
From there, you can see a bunch of familiar things that you'd see floating around any Python program, variables and functions. There are a series of variables with information about the car and a couple of methods(functions) describing what the car can do. You can see that each of the methods takes two parameters, self and speed. You can see that "speed" is used in the methods to print out how fast the car is going, but "self" is different.
What is Self?Alright, so "self" is the biggest quirk in the way that Python handles Object Oriented Programming. In most languages, classes and objects are just aware of their variables in their methods. Python needs to be told to remember them. When you pass "self" to a method, you are essentially passing that object to its method to remind it of all of the variables and other methods in that object. You also need to use it when using variables in methods. For example, if you wanted to output the model of the car along with the speed, it looks like this.
print("Your %s is moving forward at %s" % (self.model, speed))It's awkward and odd, but it works, and it's really not worth worrying about. Just remember to include "self" as the first parameter of your methods and "self." in front of your variables, and you'll be alright.
Using A ClassYou're ready to start using the car class. Create a new Python file and paste the class in. Below, you can create an object using it. Creating, or instantiating, an object in Python looks like the line below.
mycar = Car()That's it. To create a new object, you just have to make a new variable and set it equal to class that you are basing your object on.
Test out your brand new 1971 Ford Pinto. Get your car object to print out its make and model.
print("%s %s" % (mycar.make mycar.model))The use of a
.between an object and its internal components is called the dot notation. It's very common in OOP. It works for methods the same way it does for variables. Try putting your car in reverse at 5mph.
mycar.move_backward('5mph')What if you want to change the color of your car? You can definitely do that too, and it works just like changing the value of any other variable. Try printing out the color of your car first. Then, change the color, and print it out again.
print("The color of my car is %s" % mycar.color) mycar.color = "green" print("The color of my car is %s" % mycar.color)Your car is green now. What about a new car? If you made a new car object, would it be green? Give it a shot.
mynewcar = Car() print("The color of my new car is %s" % mynewcar.color)That one's orange. New objects are copied from the class, and the class still says that the color is orange. Objects exist in the computer's memory while a program is running. When you change the values within an object, they are specific to that object as it exists in memory. The changes won't persist once the program stops and won't change the class that it was created from.
Closing ThoughtsThat's enough on classes for now. Obviously, there's a lot more to cover, but you should take some time to familiarize with everything covered so far. Try the exercises below to manipulate the "car" class and familiarize yourself with how classes and objects work in Python.
- Create a new car object and change its color to red.
- Make your car move forward at 15mph.
- Put an automatic transmission in your car.
- Create a new car. Use a boolean operator to compare the colors of the cars.
- Change the
move_backwardmethod to include the model of the car.