Python Classes and Objects

Python Classes and Objects Tutorial

Classes and Objects are the building blocks of Object-Oriented Programming (OOP) in Python. A class defines a blueprint for creating objects, and an object is an instance of a class.


1. Creating a Class and Object

A class is created using the class keyword, and objects are created from that class.

Example: Defining a Class and Creating an Object

class Car:
    def __init__(self, brand, model):
        self.brand = brand
        self.model = model

    def display(self):
        print(f"Car: {self.brand} {self.model}")

# Creating an object
car1 = Car("Toyota", "Corolla")
car1.display()  # Output: Car: Toyota Corolla

__init__() is a constructor method that initializes object properties.
✅ The object car1 is an instance of the Car class.


2. Class Attributes vs. Instance Attributes

  • Class attributes are shared among all objects of the class.
  • Instance attributes are unique to each object.
class Car:
    wheels = 4  # Class attribute

    def __init__(self, brand):
        self.brand = brand  # Instance attribute

car1 = Car("Honda")
car2 = Car("Ford")

print(car1.wheels)  # Output: 4 (Shared)
print(car2.brand)   # Output: Ford (Unique)

wheels is a class attribute (common for all cars).
brand is an instance attribute (specific to each car).


3. Instance Methods and Class Methods

There are three types of methods in a class:

  • Instance Methods → Works on object attributes (self).
  • Class Methods → Works on class attributes (cls).
  • Static Methods → No access to class or instance data.

Example: Instance, Class, and Static Methods

class Person:
    species = "Human"  # Class attribute

    def __init__(self, name, age):
        self.name = name
        self.age = age

    def greet(self):  # Instance method
        return f"Hello, my name is {self.name}"

    @classmethod
    def get_species(cls):  # Class method
        return cls.species

    @staticmethod
    def is_adult(age):  # Static method
        return age >= 18

# Creating an object
p1 = Person("Alice", 25)

print(p1.greet())         # Output: Hello, my name is Alice
print(Person.get_species())  # Output: Human
print(Person.is_adult(20))   # Output: True

Instance Method → Works on self.
Class Method → Works on cls.
Static Method → No need for self or cls.


4. Inheritance (Extending Classes)

A class can inherit properties and methods from another class.

Example: Parent and Child Class

class Animal:
    def speak(self):
        return "Animal makes a sound"

class Dog(Animal):  # Dog inherits from Animal
    def speak(self):
        return "Woof! Woof!"

dog = Dog()
print(dog.speak())  # Output: Woof! Woof!

✅ The Dog class overrides the speak() method of Animal.


5. Encapsulation (Private and Protected Attributes)

  • Public (name) → Accessible anywhere.
  • Protected (_name) → Should be used within the class or subclasses.
  • Private (__name) → Cannot be accessed directly outside the class.
class Person:
    def __init__(self, name, age):
        self.name = name        # Public
        self._age = age         # Protected
        self.__salary = 50000   # Private

    def get_salary(self):
        return self.__salary

p1 = Person("John", 30)

print(p1.name)        # Output: John (Public)
print(p1._age)        # Output: 30 (Protected, but accessible)
print(p1.get_salary())  # Output: 50000 (Accessing private attribute via method)

Private attributes (__salary) can be accessed only through class methods.


6. Polymorphism (Same Method, Different Behavior)

Different classes can have methods with the same name but different behavior.

class Bird:
    def fly(self):
        return "Birds can fly"

class Penguin(Bird):
    def fly(self):
        return "Penguins cannot fly"

bird = Bird()
penguin = Penguin()

print(bird.fly())   # Output: Birds can fly
print(penguin.fly()) # Output: Penguins cannot fly

Method Overriding allows different behaviors for the fly() method.


7. Operator Overloading (+, -, *, etc.)

Python allows overloading operators using dunder methods.

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __add__(self, other):
        return Point(self.x + other.x, self.y + other.y)

p1 = Point(2, 3)
p2 = Point(4, 5)

result = p1 + p2  # Calls __add__()
print(result.x, result.y)  # Output: 6 8

The + operator is customized for Point objects.


8. Deleting an Object (del)

You can delete an object using del.

class Car:
    def __init__(self, brand):
        self.brand = brand

car1 = Car("BMW")
del car1  # Deletes car1 object

Conclusion

  • Classes are used to create objects with attributes and methods.
  • Objects are instances of classes with unique properties.
  • OOP features like inheritance, polymorphism, and encapsulation make code modular and reusable.

🚀 Mastering classes and objects will help you build complex applications efficiently!

Share on Google Plus

About It E Research

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment