Objects

In Python, everything is an object. This topic explores the concept of objects, how they are created, and their significance in Python programming.

Key Concepts

Object Creation

Understanding how to create and initialize objects using classes.

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

my_car = Car("Toyota")
print(my_car.brand)

Attributes

Defining properties of objects that hold data.

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

p = Person("Alice", 25)
print(p.name, p.age)

Methods

Functions defined within a class that operate on its objects.

class Person:
    def greet(self):
        print("Hello!")

p = Person()
p.greet()

Instance vs Class Variables

Difference between instance-specific and class-wide variables.

class Dog:
    species = "Canine"  # Class variable

    def __init__(self, name):
        self.name = name  # Instance variable

dog1 = Dog("Buddy")
dog2 = Dog("Max")

print(dog1.name, dog1.species)
print(dog2.name, dog2.species)

Encapsulation

Bundling data and methods together while restricting access to some components.

class Account:
    def __init__(self, balance):
        self.__balance = balance  # Private attribute

    def get_balance(self):
        return self.__balance

acc = Account(1000)
print(acc.get_balance())

Inheritance

Creating new classes based on existing ones to promote code reuse.

class Animal:
    def speak(self):
        print("Some sound")

class Cat(Animal):
    def speak(self):
        print("Meow")

c = Cat()
c.speak()

Polymorphism

Using a unified interface for different data types or classes.

class Bird:
    def make_sound(self):
        print("Tweet")

class Lion:
    def make_sound(self):
        print("Roar")

def sound(animal):
    animal.make_sound()

sound(Bird())
sound(Lion())

Magic Methods

Special methods that allow operator overloading and advanced class behavior.

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

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

    def __str__(self):
        return f"({self.x}, {self.y})"

v1 = Vector(2, 3)
v2 = Vector(1, 1)
print(v1 + v2)