A class is a blueprint for creating objects. It defines the structure (data) and behavior (functions) that the objects created from it will have.
Example:
class Dog:
# class attribute (shared by all objects)
species = "Canine"
# constructor (called when creating an object)
def __init__(self, name, age):
self.name = name # instance attribute
self.age = age
# instance method
def bark(self):
print(f"{self.name} says woof!")
2. What is an Object?
An object (also called an instance) is a real-world entity created from a class. Each object has its own unique data.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
1. What is a Class?
A class is a blueprint for creating objects. It defines the structure (data) and behavior (functions) that the objects created from it will have.
Example:
2. What is an Object?
An object (also called an instance) is a real-world entity created from a class. Each object has its own unique data.
Example:
Each
Dogobject has its ownnameandage, but both share the samespeciesattribute.3. Class vs Instance Attributes
species = "Canine"self.name,self.ageExample:
Changing
speciesin the class affects all dogs (unless overridden).4. Methods in Classes
self)cls)Example:
Usage:
5. Special Methods (a.k.a. Magic or Dunder Methods)
Python classes can have “special” methods that start and end with double underscores.
__init____str__print())__len__len(obj)__add__obj1 + obj2Example:
6. Inheritance (OOP Concept)
A child class can inherit attributes and methods from a parent class.
Example: