In Python, everything is an object. This topic explores the concept of objects, how they are created, and their significance in Python programming.
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)
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)
Functions defined within a class that operate on its objects.
class Person:
def greet(self):
print("Hello!")
p = Person()
p.greet()
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)
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())
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()
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())
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)