Classes and Objects
In this class, we will delve into object-oriented programming (OOP), which is a programming paradigm that uses objects to create programs.
OOP Basics Link to heading
- Class: It is a model that defines the characteristics and behavior of an object.
- Object: It is an instance of a class that has its own characteristics and behavior.
- Attribute: It is a variable that defines a characteristic of an object.
- Method: It is a function that defines a behavior of an object.
Creating a class Link to heading
class ClassName:
"""Class documentation"""
# Attributes
# Methods
Example: Link to heading
class Person:
"""Class that defines a Person object."""
# Attributes
name = ""
age = 0
# Methods
def greet(self):
"""Method that prints a personalized greeting."""
print(f"Hello, my name is {self.name} and I am {self.age} years old.")
person1 = Person()
person1.name = "Ana"
person1.age = 25
person2 = Person()
person2.name = "John"
person2.age = 30
person1.greet()
person2.greet()
Exit: Link to heading
Hello, my name is Ana and I am 25 years old.
Hello, my name is John and I am 30 years old.
In this example:
- A class called
Person
is defined that has two attributes (name
andage
) and a method (greet
). - Two objects of the
Person
class are created (person1
andperson2
). - Values are assigned to the attributes of the objects.
- The
greet
method of the objects is called.
Inheritance Link to heading
Inheritance is a mechanism that allows one class to inherit the attributes and methods of another class.
Example: Link to heading
class Student(Person):
def __init__(self, name, age, race):
super().__init__(name, age)
self.career = career
def study(self):
print(f"I am studying {self.career}.")
student1 = Student("Ana", 25, "Engineering")
student1.greet()
student1.study()
Exit: Link to heading
Hello, my name is Ana and I am 25 years old.
I am studying engineering.
In this example:
- A class
Student
is defined that inherits from the classPerson
. - The class
Student
has a new attribute:career
. - The class
Student
has a new method:study
.
Exercise Link to heading
Defines a Car class with the attributes make, model and license plate.