Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Intro to Object-Oriented Programming (OOP) in Python Show
Object-oriented programming (OOP) is a method of structuring a program by bundling related properties and behaviors into individual objects. In this tutorial, you’ll learn the basics of object-oriented programming in Python. Conceptually, objects are like the components of a system. Think of a program as a factory assembly line of sorts. At each step of the assembly line a system component processes some material, ultimately transforming raw material into a finished product. An object contains data, like the raw or preprocessed materials at each step on an assembly line, and behavior, like the action each assembly line component performs. In this tutorial, you’ll learn how to:
What Is Object-Oriented Programming in Python?Object-oriented programming is a programming paradigm that provides a means of structuring programs so that properties and behaviors are bundled into individual objects. For instance, an object could represent a person with properties like a name, age, and address and behaviors such as walking, talking, breathing, and running. Or it could represent an email with properties like a recipient list, subject, and body and behaviors like adding attachments and sending. Put another way, object-oriented programming is an approach for modeling concrete, real-world things, like cars, as well as relations between things, like companies and employees, students and teachers, and so on. OOP models real-world entities as software objects that have some data associated with them and can perform certain functions. Another common programming paradigm is procedural programming, which structures a program like a recipe in that it provides a set of steps, in the form of functions and code blocks, that flow sequentially in order to complete a task. The key takeaway is that objects are at the center of object-oriented programming in Python, not only representing the data, as in procedural programming, but in the overall structure of the program as well. Define a Class in PythonPrimitive data structures—like numbers, strings, and lists—are designed to represent simple pieces of information, such as the cost of an apple, the name of a poem, or your favorite colors, respectively. What if you want to represent something more complex? For example, let’s say you want to track employees in an organization. You need to store some basic information about each employee, such as their name, age, position, and the year they started working. One way to do this is to represent each employee as a list:
There are a number of issues with this approach. First, it can make larger code files more difficult to manage. If you reference Second, it can
introduce errors if not every employee has the same number of elements in the list. In the A great way to make this type of code more manageable and more maintainable is to use classes. Classes vs InstancesClasses are used to create user-defined data structures. Classes define functions called methods, which identify the behaviors and actions that an object created from the class can perform with its data. In this tutorial, you’ll create a A class is a blueprint for how something should be defined. It doesn’t actually contain any data. The While the class is the blueprint, an instance is an object that is built from a class and contains real data. An instance of the Put another way, a class is like a form or questionnaire. An instance is like a form that has been filled out with information. Just like many people can fill out the same form with their own unique information, many instances can be created from a single class. How to Define a ClassAll class definitions start with the Here’s an example of a The body of the The The properties that all You can give Let’s update the
Notice that the In the body of
Attributes created in On the other hand, class attributes are attributes that have the same value for all class instances. You can define a class attribute by assigning a value to a variable name outside of For example, the following
Class attributes are defined directly beneath the first line of the class name and are indented by four spaces. They must always be assigned an initial value. When an instance of the class is created, class attributes are automatically created and assigned to their initial values. Use class attributes to define properties that should have the same value for every class instance. Use instance attributes for properties that vary from one instance to another. Now that we have a Instantiate an Object in PythonOpen IDLE’s interactive window and type the following: >>>
This creates a new Creating a new object from a class is called instantiating an object. You can instantiate a new >>>
You now have a new Now instantiate a second >>>
The new To see this another way, type the following: >>>
In this code, you create two new Class and Instance AttributesNow create a new >>>
To
instantiate objects of this >>>
To pass arguments to the >>>
This creates two new The When you instantiate a After you create the >>>
You can access class attributes the same way: >>>
One of the biggest advantages of using classes to organize data is that instances are guaranteed to have the attributes you expect. All Although the attributes are guaranteed to exist, their values can be changed dynamically: >>>
In this example, you change the The key takeaway here is that custom objects are mutable by default. An object is mutable if it can be altered dynamically. For example, lists and dictionaries are mutable, but strings and tuples are immutable. Instance MethodsInstance methods are functions that are defined inside a class and can only be called from an instance of that class. Just like Open a new editor window in IDLE and type in the following
This
Save the modified >>>
In the above When you create a >>>
Let’s see what happens when you >>>
When you In the editor window, change the name of the
Save the file and press F5. Now, when you >>>
Methods like In the next section, you’ll see how to take your knowledge one step further and create classes from other classes. Check Your UnderstandingExpand the block below to check your understanding: Create a
Then instantiate two
You can expand the block below to see a solution: First, create a
The Now you can create the two
The To print the color and mileage of each
The
f-string in the above The final output looks like this:
When you’re ready, you can move on to the next section. Inherit From Other Classes in PythonInheritance is the process by which one class takes on the attributes and methods of another. Newly formed classes are called child classes, and the classes that child classes are derived from are called parent classes. Child classes can override or extend the attributes and methods of parent classes. In other words, child classes inherit all of the parent’s attributes and methods but can also specify attributes and methods that are unique to themselves. Although the analogy isn’t perfect, you can think of object inheritance sort of like genetic inheritance. You may have inherited your hair color from your mother. It’s an attribute you were born with. Let’s say you decide to color your hair purple. Assuming your mother doesn’t have purple hair, you’ve just overridden the hair color attribute that you inherited from your mom. You also inherit, in a sense, your language from your parents. If your parents speak English, then you’ll also speak English. Now imagine you decide to learn a second language, like German. In this case you’ve extended your attributes because you’ve added an attribute that your parents don’t have. Dog Park ExamplePretend for a moment that you’re at a dog park. There are many dogs of different breeds at the park, all engaging in various dog behaviors. Suppose now that you want to model the dog park with
Python classes. The You could modify the
The instance methods defined earlier are omitted here because they aren’t important for this discussion. Press F5 to save the file. Now you can model the dog park by instantiating a bunch of different dogs in the interactive window: >>>
Each breed of dog has slightly different behaviors. For example, bulldogs have a low bark that sounds like woof, but dachshunds have a higher-pitched bark that sounds more like yap. Using just the >>>
Passing a string to every call to You can simplify the experience of working with the Parent Classes vs Child ClassesLet’s create a child class for each of the three breeds mentioned above: Jack Russell Terrier, Dachshund, and Bulldog. For
reference, here’s the full definition of the
Remember, to create a child class, you create new class with its own name and then put the name of the parent class in parentheses. Add the following to the
Press F5 to save and run the file. With the child classes defined, you can now instantiate some dogs of specific breeds in the interactive window: >>>
Instances of child classes inherit all of the attributes and methods of the parent class: >>>
To determine which class a given object belongs to, you can use the built-in >>>
What if you want to determine
if >>>
Notice that The >>>
More generally, all objects created from a child class are instances of the parent class, although they may not be instances of other child classes. Now that you’ve created child classes for some different breeds of dogs, let’s give each breed its own sound. Extend the Functionality of a Parent ClassSince different breeds of dogs have slightly different barks, you want to provide a default value for the To override a method defined on the parent class, you define a method
with the same name on the child class. Here’s what that looks like for the
Now Update >>>
Sometimes dogs make different barks, so if Miles gets angry and growls, you can still call >>>
One thing to keep in mind about class inheritance is that changes to the parent class automatically propagate to child classes. This occurs as long as the attribute or method being changed isn’t overridden in the child class. For example, in the editor window,
change the string returned by
Save the file and press F5. Now, when you create a new >>>
However, calling >>>
Sometimes it makes sense to completely override a method from a parent class. But in this instance, we don’t want the To do this, you still need to define a You can access the parent class from inside a method of a child class by using
When you call Update >>>
Now when you call Check Your UnderstandingExpand the block below to check your understanding: Create a
You can expand the block below to see a solution: Create a class called
The ConclusionIn this tutorial, you learned about object-oriented programming (OOP) in Python. Most modern programming languages, such as Java, C#, and C++, follow OOP principles, so the knowledge you gained here will be applicable no matter where your programming career takes you. In this tutorial, you learned how to:
If you enjoyed what you learned in this sample from Python Basics: A Practical Introduction to Python 3, then be sure to check out the rest of the book. Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Intro to Object-Oriented Programming (OOP) in Python Which of the following is the blueprint for creating objects?In object-oriented programming, a class is a blueprint for creating objects (a particular data structure), providing initial values for state (member variables or attributes), and implementations of behavior (member functions or methods).
Can be thought of as a blueprint that can be used to create?A class can be thought of as a blueprint that can be used to create an object.
How is a class like a blueprint quizlet?A class is the blueprint for an object. It specifies the fields and methods a particular type of object has.
What is meant by the statement a class is like a blueprint?Once a class has been defined, it serves as a template, or blueprint, for creating individual objects or instances of the class.
|