From the course: Advanced Python Projects: Build AI Applications
A refresher of object-oriented programming concepts - Python Tutorial
From the course: Advanced Python Projects: Build AI Applications
A refresher of object-oriented programming concepts
- [Instructor] In this lesson, I'm going to provide a quick refresher of the fundamental concepts of object-oriented programming. If you're quite familiar with these concepts, feel free to move directly to the next lesson. So let's get started. We are going to create a new class called Car, class Car. A constructor is a special method in a class that is automatically called when an object is created. Let's define def __init__ self, make, model, close it with a colon. The self here reference to the car that's being created. We're storing the make and the model information in the car. The next concept that we'll explore is encapsulation. Encapsulation heights the internal details of an object and exposes only what is necessary. Think of it as specifying the unique characteristic of each car. Self.make equals make, self.model equals model. A method is like a function inside the class. It's something the car can do, like starting its engine. So let's define a method, start_engine self. Now let's print using the method. Print f the self.make self.model model's engine is running. Here it is accessing attributes through self. This is like the car performing an action specific to itself. Next, let's create instances of the car class. Before we do that, the next concept that we'll explore is inheritance. Inheritance enables code reuse and creation of hierarchy of classes. Car is a class that can be used to create objects. So let's create our objects. Car1 equals car, Toyota comma Camry, car2 Ford comma Mustang. So let's print using the objects we created. Print f I have a car1.make car1.model period, and then close the quotations. In the next line, we'll print, I also own a car2.make car2.model. Next we'll explore polymorphism. Polymorphism is the ability of objects of different classes to be treated as objects of a common base class. This is when different objects such as car1 and car2 can perform the same action, start_engine. So car1.start_engine, close parentheses, car2.start_engine. This is like instructing each car to engage its engine and they follow their unique set of instructions. So now let's run the code to see what happens. The first two lines of output are from the print statements in 19 and 20. The next two outputs are from the print statement in line 12. I hope this lesson provided you a good overview of object-oriented programming concepts to help you prepare for building the projects that are upcoming.
Practice while you learn with exercise files
Download the files the instructor uses to teach the course. Follow along and learn by watching, listening and practicing.