Lesson 1: Classes and Objects

In this lesson, we will introduce Object-Oriented Programming (OOP) concepts in Python by focusing on Classes and Objects. OOP is a programming paradigm that organizes software design around data, or objects, rather than functions and logic. A class is like a blueprint for creating objects, and an object is an instance of a class.

By the end of this lesson, you will understand how to define a class, create objects, and use methods and attributes to manipulate data in Python.

1. Creating Classes

A class in Python is a template or blueprint for creating objects. It defines the properties (attributes) and behaviors (methods) that the objects created from the class will have.

To define a class, you use the class keyword, followed by the class name. By convention, class names are written in CamelCase (i.e., the first letter of each word is capitalized, and no spaces are used between words).

Syntax:
python
class ClassName:

# attributes

# methods

 

Example:
python
class Car:

# Class attribute (shared by all instances)

wheels = 4

 

# Initializer (Constructor)

def __init__(self, make, model, year):

# Instance attributes (specific to each instance)

self.make = make

self.model = model

self.year = year

 

# Method to display the car details

def display_info(self):

print(f”{self.year} {self.make} {self.model}”)

 

In the above code:

  • Caris the class name.
  • wheelsis a class attribute shared by all instances of the Car
  • The __init__()method is the constructor that initializes the object’s attributes (make, model, and year). The self keyword refers to the current instance of the class.
  • display_info()is a method that prints the details of the car object.

2. Instantiating Objects

Once you have created a class, you can create instances of that class, known as objects. Creating an object from a class is called instantiation. Each object can hold its own data, but they share the same structure as defined by the class.

To instantiate an object, you simply call the class as if it were a function, passing any required arguments to the constructor.

Syntax:
python
object_name = ClassName(arguments)

 

Example:
python
# Creating an object of the Car class

my_car = Car(“Toyota”, “Corolla”, 2021)

 

# Accessing attributes and methods of the object

print(my_car.make)  # Output: Toyota

my_car.display_info()  # Output: 2021 Toyota Corolla

 

In this example:

  • We created an object called my_carfrom the Car class and passed the arguments “Toyota”, “Corolla”, and 2021 to the __init__()
  • We accessed the makeattribute of the my_car object and called the display_info()

3. Methods and Attributes

In object-oriented programming, attributes are the variables associated with a class or an object, and methods are the functions defined within a class that describe the behaviors of an object.

Attributes:

Attributes are values that belong to an object. There are two types of attributes:

  • Instance attributes: Specific to each instance of the class.
  • Class attributes: Shared by all instances of the class.
Example of Instance and Class Attributes:
python
class Car:

# Class attribute

wheels = 4

 

def __init__(self, make, model, year):

# Instance attributes

self.make = make

self.model = model

self.year = year

 

def display_info(self):

print(f”{self.year} {self.make} {self.model}”)

 

# Creating two objects

car1 = Car(“Honda”, “Civic”, 2020)

car2 = Car(“Ford”, “Mustang”, 2021)

 

# Accessing instance attributes

print(car1.make)  # Output: Honda

print(car2.model)  # Output: Mustang

 

# Accessing class attribute

print(car1.wheels)  # Output: 4

print(car2.wheels)  # Output: 4

 

# Changing class attribute

Car.wheels = 5

 

# Accessing updated class attribute

print(car1.wheels)  # Output: 5

print(car2.wheels)  # Output: 5

 

  • In this example:
    • wheelsis a class attribute and is shared by all instances of the Car
    • make, model, and yearare instance attributes and are unique to each object created from the Car
    • Modifying the wheelsattribute in the class affects all instances.
Methods:

Methods are functions that are defined inside a class and are used to perform actions on objects created from that class. Methods typically have at least one parameter, self, which refers to the current instance of the class.

Example:
python
class Dog:

def __init__(self, name, breed):

self.name = name

self.breed = breed

 

def bark(self):

print(f”{self.name} says Woof!”)

 

# Creating an object

dog1 = Dog(“Buddy”, “Golden Retriever”)

 

# Calling the bark method

dog1.bark()  # Output: Buddy says Woof!

 

  • In this example, bark()is a method that performs an action (printing a message) using the name attribute of the Dog

4. Self and Instance Methods

  • self: The selfparameter in methods is a reference to the current instance of the class. It is used to access instance attributes and other methods within the class. It allows each object to keep track of its own data.
Example of Self:
python
class Circle:

def __init__(self, radius):

self.radius = radius  # Instance attribute

 

def area(self):

return 3.14 * self.radius ** 2  # Using self to access instance attribute

 

# Creating an object

circle = Circle(5)

 

# Calling the area method

print(circle.area())  # Output: 78.5

 

In this example:

  • The area()method calculates the area of the circle using the radius instance attribute.

5. Modifying Methods and Attributes

You can modify the attributes of an object by directly accessing them or using methods within the class.

Example:
python

class Person:

def __init__(self, name, age):

self.name = name

self.age = age

 

def birthday(self):

self.age += 1  # Increasing the age by 1

 

# Creating an object

person1 = Person(“Alice”, 30)

 

# Accessing and modifying attributes

print(person1.age)  # Output: 30

person1.birthday()

print(person1.age)  # Output: 31

 

  • In this example, we used the birthday()method to modify the age attribute of the person1

6. Conclusion

In this lesson, we have covered:

  • Classes: The structure and blueprint for creating objects.
  • Objects: Instances of a class with their own data and behaviors.
  • Attributes: Data stored in an object (instance attributes) or shared across all objects of a class (class attributes).
  • Methods: Functions defined inside a class that describe the behaviors of objects.
  • Self: A reference to the current instance of a class used to access attributes and methods.

Understanding classes and objects is fundamental to working with Object-Oriented Programming in Python. In the next lesson, we will dive deeper into other OOP concepts such as inheritance, polymorphism, and encapsulation.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *