Python Classes and Objects
Last Updated :
23 Jul, 2025
In Python, classes and objects are the core of object-oriented programming. A class defines the structure and behavior of objects, while objects are instances of these classes. Understanding how to create and use classes is essential for writing clean, maintainable code. In this article, we’ll cover key concepts like class variables, instance variables, methods, and more, giving you a strong foundation in Python’s object-oriented approach.
Python Classes and ObjectsClasses and Objects
What is a Class?
A class in Python is a user-defined template for creating objects. It bundles data and functions together, making it easier to manage and use them. When we create a new class, we define a new type of object. We can then create multiple instances of this object type.
Classes and Objects (Here Dog is the Base Class and Bobby is Object)
Classes are created using class keyword. Attributes are variables defined inside the class and represent the properties of the class. Attributes can be accessed using the dot . operator (e.g., MyClass.my_attribute).
Python
# define a class
class Dog:
sound = "bark" # class attribute
What is an Object?
An object is a specific instance of a class. It holds its own set of data (instance variables) and can invoke the methods defined by its class. Multiple objects can be created from the same class, each with its own unique attributes.
Let's create an object from the Dog class.
Python
class Dog:
sound = "bark"
# Create an object from the class
dog1 = Dog()
# Access the class attribute
print(dog1.sound)
In the above sample code sound attribute is a class attribute. It is shared across all instances of Dog class, so can be directly accessed through instance dog1.
Why do we need Python Classes and Objects
- Supports object-oriented programming using reusable templates (classes) and real-world models (objects).
- Promotes code reusability and modular design with organized methods and attributes.
- Simplifies complex programs by grouping related data and behavior.
- Enables key OOP concepts like inheritance, encapsulation and polymorphism.
Using __init__() Function
In Python, class has __init__() function which automatically initializes object attributes when an object is created. The __init__()
method is the constructor in Python.
Python
class Dog:
species = "Canine" # Class attribute
def __init__(self, name, age):
self.name = name # Instance attribute
self.age = age # Instance attribute
Explanation:
- class Dog: Defines a class named Dog.
- species: A class attribute shared by all instances of the class.
- __init__ method: Initializes the name and age attributes when a new object is created.
Initiate Object with __init__()
Python
class Dog:
species = "Canine" # Class attribute
def __init__(self, name, age):
self.name = name # Instance attribute
self.age = age # Instance attribute
# Creating an object of the Dog class
dog1 = Dog("Buddy", 3)
print(dog1.name) # Output: Buddy
print(dog1.species) # Output: Canine
Explanation:
- dog1 = Dog("Buddy", 3): Creates an object of the Dog class with name as "Buddy" and age as 3.
- dog1.name: Accesses the instance attribute name of the dog1 object.
- dog1.species: Accesses the class attribute species of the dog1 object.
Self Parameter
self parameter is a reference to the current instance of the class. It allows us to access the attributes and methods of the object.
Python
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def bark(self):
print(f"{self.name} is barking!")
# Creating an instance of Dog
dog1 = Dog("Buddy", 3)
dog1.bark()
Explanation:
- Inside bark(), self.name accesses the specific dog's name and prints it.
- When we call dog1.bark(), Python automatically passes dog1 as self, allowing access to its attributes.
__str__() Method
__str__ method in Python allows us to define a custom string representation of an object. By default, when we print an object or convert it to a string using str(), Python uses the default implementation, which returns a string like <__main__.ClassName object at 0x00000123>.
Python
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f"{self.name} is {self.age} years old." # Correct: Returning a string
dog1 = Dog("Buddy", 3)
dog2 = Dog("Charlie", 5)
print(dog1)
print(dog2)
Explanation:
- __str__ Implementation: Defined as a method in the Dog class. Uses the self parameter to access the instance's attributes (name and age).
- Readable Output: When print(dog1) is called, Python automatically uses the __str__ method to get a string representation of the object. Without __str__, calling print(dog1) would produce something like <__main__.Dog object at 0x00000123>.
Class and Instance Variables in Python
In Python, variables defined in a class can be either class variables or instance variables, and understanding the distinction between them is crucial for object-oriented programming.
Class Variables
These are the variables that are shared across all instances of a class. It is defined at the class level, outside any methods. All objects of the class share the same value for a class variable unless explicitly overridden in an object.
Instance Variables
Variables that are unique to each instance (object) of a class. These are defined within __init__() method or other instance methods. Each object maintains its own copy of instance variables, independent of other objects.
Example:
Python
class Dog:
# Class variable
species = "Canine"
def __init__(self, name, age):
# Instance variables
self.name = name
self.age = age
# Create objects
dog1 = Dog("Buddy", 3)
dog2 = Dog("Charlie", 5)
# Access class and instance variables
print(dog1.species) # (Class variable)
print(dog1.name) # (Instance variable)
print(dog2.name) # (Instance variable)
# Modify instance variables
dog1.name = "Max"
print(dog1.name) # (Updated instance variable)
# Modify class variable
Dog.species = "Feline"
print(dog1.species) # (Updated class variable)
print(dog2.species)
Explanation:
- Class Variable (species): Shared by all instances of the class. Changing Dog.species affects all objects, as it's a property of the class itself.
- Instance Variables (name, age): Defined in the __init__() method. Unique to each instance (e.g., dog1.name and dog2.name are different).
- Accessing Variables: Class variables can be accessed via the class name (Dog.species) or an object (dog1.species). Instance variables are accessed via the object (dog1.name).
- Updating Variables: Changing Dog.species affects all instances. Changing dog1.name only affects dog1 and does not impact dog2.
Additional Important Concepts in Python Classes and Objects
Getter and Setter Methods
Getter and Setter methods provide controlled access to an object's attributes. In Python, these methods are used to retrieve (getter
) or modify (setter
) the values of private attributes, allowing for data encapsulation.
Python doesn't have explicit get
and set
methods like other languages, but it supports this functionality using property decorators.
- Getter: Used to access the value of an attribute.
- Setter: Used to modify the value of an attribute.
Python
class Dog:
def __init__(self, name, age):
self._name = name # Conventionally private variable
self._age = age # Conventionally private variable
@property
def name(self):
return self._name # Getter
@name.setter
def name(self, value):
self._name = value # Setter
@property
def age(self):
return self._age # Getter
@age.setter
def age(self, value):
if value < 0:
print("Age cannot be negative!")
else:
self._age = value # Setter
Method Overriding
Method overriding occurs when a subclass provides a specific implementation of a method that is already defined in its superclass. This allows subclasses to modify or extend the behavior of inherited methods.
Python
class Animal:
def sound(self):
print("Some sound")
class Dog(Animal):
def sound(self): # Method overriding
print("Woof")
dog = Dog()
dog.sound() # Output: Woof
Static Methods and Class Methods
Static methods and class methods are bound to the class, not instances of the class.
- Static Method: A method that does not require access to the instance or class. It’s defined using the
@staticmethod
decorator. - Class Method: A method that receives the class as its first argument (
cls
). It’s defined using the @classmethod
decorator.
Python
class Dog:
@staticmethod
def info():
print("Dogs are loyal animals.")
@classmethod
def count(cls):
print(f"There are many dogs of class {cls}.")
dog = Dog()
dog.info() # Static method call
dog.count() # Class method call
Abstract Classes and Interfaces
Abstract classes provide a template for other classes. These classes can't be instantiated directly. They contain abstract methods, which are methods that must be implemented by subclasses.
Abstract classes are defined using the abc
module in Python.
Python
from abc import ABC, abstractmethod
class Animal(ABC):
@abstractmethod
def sound(self):
pass
class Dog(Animal):
def sound(self):
print("Woof")
dog = Dog()
dog.sound() # Output: Woof
Class Variables vs. Instance Variables
- Class Variables are shared by all instances of a class. They are defined inside the class but outside any methods.
- Instance Variables are unique to each instance and are defined in the
__init__()
method.
Python
class Dog:
species = "Canine" # Class variable
def __init__(self, name, age):
self.name = name # Instance variable
self.age = age # Instance variable
dog1 = Dog("Buddy", 3)
dog2 = Dog("Lucy", 2)
print(dog1.species) # Accessing class variable
print(dog2.name) # Accessing instance variable
Python
class MyClass:
def __init__(self, arg1, arg2):
self.arg1 = arg1
self.arg2 = arg2
def some_method(self):
# Method definition
pass
Q: What is an object in OOP?
A: In Object-Oriented Programming (OOP), an object is a tangible entity that represents a particular instance of a class. It combines data (attributes) and behaviors (methods) specified by the class.
Q: Why do we need classes and objects?
A: Classes and objects provide a way to model real-world entities and abstract concepts in code. They promote code organization, encapsulation (data hiding), inheritance (code reuse), and polymorphism (method overriding), making complex systems easier to manage and extend.
Similar Reads
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. OOPs is a way of organizing code that uses objects and classes to represent real-world entities and their behavior. In OOPs, object has attributes thing th
11 min read
Python Classes and Objects In Python, classes and objects are the core of object-oriented programming. A class defines the structure and behavior of objects, while objects are instances of these classes. Understanding how to create and use classes is essential for writing clean, maintainable code. In this article, weâll cover
9 min read
Python objects A class is a user-defined blueprint or prototype from which objects are created. Classes provide a means of bundling data and functionality together. Creating a new class creates a new type of object, allowing new instances of that type to be made. Each class instance can have attributes attached to
2 min read
Class and Object
self in Python classIn Python, self is a fundamental concept when working with object-oriented programming (OOP). It represents the instance of the class being used. Whenever we create an object from a class, self refers to the current object instance. It is essential for accessing attributes and methods within the cla
6 min read
Class and Instance Attributes in PythonClass attributes: Class attributes belong to the class itself they will be shared by all the instances. Such attributes are defined in the class body parts usually at the top, for legibility. Python # Write Python code here class sampleclass: count = 0 # class attribute def increase(self): samplecla
2 min read
Create a Python SubclassIn Python, a subclass is a class that inherits attributes and methods from another class, known as the superclass or parent class. When you create a subclass, it can reuse and extend the functionality of the superclass. This allows you to create specialized versions of existing classes without havin
3 min read
Inner Class in PythonPython is an Object-Oriented Programming Language, everything in Python is related to objects, methods, and properties. A class is a user-defined blueprint or a prototype, which we can use to create the objects of a class. The class is defined by using the class keyword.Example of classPython# creat
5 min read
Python MetaClassesThe key concept of python is objects. Almost everything in python is an object, which includes functions and as well as classes. As a result, functions and classes can be passed as arguments, can exist as an instance, and so on. Above all, the concept of objects let the classes in generating other c
9 min read
Creating Instance Objects in PythonIn Python, an instance object is an individual object created from a class, which serves as a blueprint defining the attributes (data) and methods (functions) for the object. When we create an object from a class, it is referred to as an instance. Each instance has its own unique data but shares the
3 min read
Dynamic Attributes in PythonDynamic attributes in Python are terminologies for attributes that are defined at runtime, after creating the objects or instances. In Python we call all functions, methods also as an object. So you can define a dynamic instance attribute for nearly anything in Python. Consider the below example for
2 min read
Constructors in PythonIn Python, a constructor is a special method that is called automatically when an object is created from a class. Its main role is to initialize the object by setting up its attributes or state. The method __new__ is the constructor that creates a new instance of the class while __init__ is the init
3 min read
Why Python Uses 'Self' as Default ArgumentIn Python, when defining methods within a class, the first parameter is always self. The parameter self is a convention not a keyword and it plays a key role in Pythonâs object-oriented structure.Example:Pythonclass Car: def __init__(self, brand, model): self.brand = brand # Set instance attribute s
3 min read
Encapsulation and Access Modifiers
Encapsulation in PythonIn Python, encapsulation refers to the bundling of data (attributes) and methods (functions) that operate on the data into a single unit, typically a class. It also restricts direct access to some components, which helps protect the integrity of the data and ensures proper usage.Encapsulation is the
6 min read
Access Modifiers in Python : Public, Private and ProtectedPrerequisites: Underscore (_) in Python, Private Variables in PythonEncapsulation is one of the four principles used in Object Oriented Paradigm. It is used to bind and hide data to the class. Data hiding is also referred as Scoping and the accessibility of a method or a field of a class can be chan
9 min read
Access Modifiers in Python : Public, Private and ProtectedPrerequisites: Underscore (_) in Python, Private Variables in PythonEncapsulation is one of the four principles used in Object Oriented Paradigm. It is used to bind and hide data to the class. Data hiding is also referred as Scoping and the accessibility of a method or a field of a class can be chan
9 min read
Private Variables in PythonPrerequisite: Underscore in PythonIn Python, there is no existence of âPrivateâ instance variables that cannot be accessed except inside an object. However, a convention is being followed by most Python code and coders i.e., a name prefixed with an underscore, For e.g. _geek should be treated as a n
3 min read
Private Methods in PythonEncapsulation is one of the fundamental concepts in object-oriented programming (OOP) in Python. It describes the idea of wrapping data and the methods that work on data within one unit. This puts restrictions on accessing variables and methods directly and can prevent the accidental modification of
6 min read
Protected variable in PythonPrerequisites: Underscore ( _ ) in Python A Variable is an identifier that we assign to a memory location which is used to hold values in a computer program. Variables are named locations of storage in the program. Based on access specification, variables can be public, protected and private in a cl
2 min read
Inheritance
Inheritance in PythonInheritance is a fundamental concept in object-oriented programming (OOP) that allows a class (called a child or derived class) to inherit attributes and methods from another class (called a parent or base class). In this article, we'll explore inheritance in Python.Inheritance in PythonWhy do we ne
7 min read
Method Overriding in PythonMethod overriding is an ability of any object-oriented programming language that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its super-classes or parent classes. When a method in a subclass has the same name, the same parameter
7 min read
Operator Overloading in PythonOperator Overloading means giving extended meaning beyond their predefined operational meaning. For example operator + is used to add two integers as well as join two strings and merge two lists. It is achievable because '+' operator is overloaded by int class and str class. You might have noticed t
8 min read
Python super()In Python, the super() function is used to refer to the parent class or superclass. It allows you to call methods defined in the superclass from the subclass, enabling you to extend and customize the functionality inherited from the parent class.Syntax of super() in PythonSyntax: super()Return : Ret
8 min read
Multiple Inheritance in PythonInheritance is the mechanism to achieve the re-usability of code as one class(child class) can derive the properties of another class(parent class). It also provides transitivity ie. if class C inherits from P then all the sub-classes of C would also inherit from P. Multiple Inheritance When a class
5 min read
What Is Hybrid Inheritance In Python?Inheritance is a fundamental concept in object-oriented programming (OOP) where a class can inherit attributes and methods from another class. Hybrid inheritance is a combination of more than one type of inheritance. In this article, we will learn about hybrid inheritance in Python. Hybrid Inheritan
3 min read
Multilevel Inheritance in PythonPython is one of the most popular and widely used Programming Languages. Python is an Object Oriented Programming language which means it has features like Inheritance, Encapsulation, Polymorphism, and Abstraction. In this article, we are going to learn about Multilevel Inheritance in Python. Pre-Re
3 min read
Multilevel Inheritance in PythonPython is one of the most popular and widely used Programming Languages. Python is an Object Oriented Programming language which means it has features like Inheritance, Encapsulation, Polymorphism, and Abstraction. In this article, we are going to learn about Multilevel Inheritance in Python. Pre-Re
3 min read
Polymorphism
Abstraction
Special Methods and Testing
Additional Resources