The Wayback Machine - https://web.archive.org/web/20241125081022/https://www.geeksforgeeks.org/python-classes-and-objects/
Open In App

Python Classes and Objects

Last Updated : 20 Nov, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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 it to maintain its state. Class instances can also have methods (defined by their class) for modifying their state.

The class creates a user-defined data structure, which holds its own data members and member functions, which can be accessed and used by creating an instance of that class. A class is like a blueprint for an object.

Creating a Python Class

Here, the class keyword indicates that you are creating a class followed by the name of the class (Dog in this case).

Python
class Dog:
    sound = "bark"

Some points on Python class:

  • Classes are created by keyword class.
  • Attributes are the variables that belong to a class.
  • Attributes are always public and can be accessed using the dot (.) operator. Eg.: My class.Myattribute


To understand the need for creating a class and object in Python let’s consider an example, let’s say you wanted to track the number of dogs that may have different attributes like breed and age. If a list is used, the first element could be the dog’s breed while the second element could represent its age. Let’s suppose there are 100 different dogs, then how would you know which element is supposed to be which? What if you wanted to add other properties to these dogs? This lacks organization and it’s the exact need for classes.

Object of Python Class

In Python programming an Object is an instance of a Class. A class is like a blueprint while an instance is a copy of the class with actual values.


obj = ClassName()
print(obj.atrr)

It’s not an idea anymore, it’s an actual dog, like a dog of breed pug who’s seven years old. You can have many dogs to create many different instances, but without the class as a guide, you would be lost, not knowing what information is required.

An object consists of:

  • State: It is represented by the attributes of an object. It also reflects the properties of an object.
  • Behavior: It is represented by the methods of an object. It also reflects the response of an object to other objects.
  • Identity: It gives a unique name to an object and enables one object to interact with other objects.

python class

Declaring Class Objects (Also called instantiating a class)

When an object of a class is created, the class is said to be instantiated. All the instances share the attributes and the behavior of the class. But the values of those attributes, i.e. the state are unique for each object. A single class may have any number of instances.

Example:

python declaring an object

Example of Python Class and object

Creating an object in Python involves instantiating a class to create a new instance of that class. This process is also referred to as object instantiation.

Python
#  instantiating a class
class Dog:

    # A simple class
    # attribute
    attr1 = "mammal"
    attr2 = "dog"

    # A sample method
    def fun(self):
        print("I'm a", self.attr1)
        print("I'm a", self.attr2)


# Driver code
# Object instantiation
Rodger = Dog()

# Accessing class attributes
# and method through objects
print(Rodger.attr1)
Rodger.fun()

Output:

mammal
I'm a mammal
I'm a dog

In the above example, an object is created which is basically a dog named Rodger. This class only has two class attributes that tell us that Rodger is a dog and a mammal.

Explanation :

In this example, we are creating a Dog class and we have created two class variables attr1 and attr2. We have created a method named fun() which returns the string “I’m a, {attr1}” and I’m a, {attr2}. We have created an object of the Dog class and we are printing at the attr1 of the object. Finally, we are calling the fun() function.

Self Parameter

When we call a method of this object as myobject.method(arg1, arg2), this is automatically converted by Python into MyClass.method(myobject, arg1, arg2) – this is all the special self is about. 

Python
class GFG:
    def __init__(self, name, company):
        self.name = name
        self.company = company

    def show(self):
        print("Hello my name is " + self.name+" and I" +
              " work in "+self.company+".")


obj = GFG("John", "GeeksForGeeks")
obj.show()

The Self Parameter does not call it to be Self, You can use any other name instead of it. Here we change the self to the word someone and the output will be the same.

Python
class GFG:
    def __init__(somename, name, company):
        somename.name = name
        somename.company = company

    def show(somename):
        print("Hello my name is " + somename.name +
              " and I work in "+somename.company+".")


obj = GFG("John", "GeeksForGeeks")
obj.show()

Output: Output for both of the codes will be the same.

Hello my name is John and I work in GeeksForGeeks.

Explanation:

In this example, we are creating a GFG class and we have created the name, and company instance variables in the constructor. We have created a method named show() which returns the string “Hello my name is ” + {name} +” and I work in “+{company}+”.”.We have created a person class object and we passing the name John and Company GeeksForGeeks to the instance variable. Finally, we are calling the show() of the class.

Pass Statement

The program’s execution is unaffected by the pass statement’s inaction. It merely permits the program to skip past that section of the code without doing anything. It is frequently employed when the syntactic constraints of Python demand a valid statement but no useful code must be executed.

Python
class MyClass:
    pass

__init__() method

The __init__ method is similar to constructors in C++ and Java. Constructors are used to initializing the object’s state. Like methods, a constructor also contains a collection of statements(i.e. instructions) that are executed at the time of Object creation. It runs as soon as an object of a class is instantiated. The method is useful to do any initialization you want to do with your object.

Python
# Sample class with init method
class Person:

    # init method or constructor
    def __init__(self, name):
        self.name = name

    # Sample Method
    def say_hi(self):
        print('Hello, my name is', self.name)


p = Person('Nikhil')
p.say_hi()

Output: 

Hello, my name is Nikhil

Explanation:

In this example, we are creating a Person class and we have created a name instance variable in the constructor. We have created a method named as say_hi() which returns the string “Hello, my name is {name}”.We have created a person class object and we pass the name Nikhil to the instance variable. Finally, we are calling the say_hi() of the class.

__str__() method

Python has a particular method called __str__(). that is used to define how a class object should be represented as a string. It is often used to give an object a human-readable textual representation, which is helpful for logging, debugging, or showing users object information. When a class object is used to create a string using the built-in functions print() and str(), the __str__() function is automatically used. You can alter how objects of a class are represented in strings by defining the __str__() method.

Python
class GFG:
    def __init__(self, name, company):
        self.name = name
        self.company = company

    def __str__(self):
        return f"My name is {self.name} and I work in {self.company}."


my_obj = GFG("John", "GeeksForGeeks")
print(my_obj)

Output:

My name is John and I work in GeeksForGeeks.

Explanation:

In this example, We are creating a class named GFG.In the class, we are creating two instance variables name and company. In the __str__() method we are returning the name instance variable and company instance variable. Finally, we are creating the object of GFG class and we are calling the __str__() method.

Class and Instance Variables

Instance variables are for data, unique to each instance and class variables are for attributes and methods shared by all instances of the class. Instance variables are variables whose value is assigned inside a constructor or method with self whereas class variables are variables whose value is assigned in the class.

Defining instance variables using a constructor. 

Python
# Python3 program to show that the variables with a value
# assigned in the class declaration, are class variables and
# variables inside methods and constructors are instance
# variables.

# Class for Dog


class Dog:

    # Class Variable
    animal = 'dog'

    # The init method or constructor
    def __init__(self, breed, color):

        # Instance Variable
        self.breed = breed
        self.color = color


# Objects of Dog class
Rodger = Dog("Pug", "brown")
Buzo = Dog("Bulldog", "black")

print('Rodger details:')
print('Rodger is a', Rodger.animal)
print('Breed: ', Rodger.breed)
print('Color: ', Rodger.color)

print('\nBuzo details:')
print('Buzo is a', Buzo.animal)
print('Breed: ', Buzo.breed)
print('Color: ', Buzo.color)

# Class variables can be accessed using class
# name also
print("\nAccessing class variable using class name")
print(Dog.animal)

Output:

Rodger details:
Rodger is a dog
Breed:  Pug
Color:  brown
Buzo details:
Buzo is a dog
Breed:  Bulldog
Color:  black
Accessing class variable using class name
dog

Explanation:

A class named Dog is defined with a class variable animal set to the string “dog”. Class variables are shared by all objects of a class and can be accessed using the class name. Dog class has two instance variables breed and color. Later we are creating two objects of the Dog class and we are printing the value of both objects with a class variable named animal.

Defining instance variables using the normal method:

Python
# Python3 program to show that we can create
# instance variables inside methods

# Class for Dog


class Dog:

    # Class Variable
    animal = 'dog'

    # The init method or constructor
    def __init__(self, breed):

        # Instance Variable
        self.breed = breed

    # Adds an instance variable
    def setColor(self, color):
        self.color = color

    # Retrieves instance variable
    def getColor(self):
        return self.color


# Driver Code
Rodger = Dog("pug")
Rodger.setColor("brown")
print(Rodger.getColor())

Output:

brown

Explanation:

In this example, We have defined a class named Dog and we have created a class variable animal. We have created an instance variable breed in the constructor. The class Dog consists of two methods setColor and getColor, they are used for creating and initializing an instance variable and retrieving the value of the instance variable. We have made an object of the Dog class and we have set the instance variable value to brown and we are printing the value in the terminal.

Conclusion

understanding Python classes and objects is fundamental for anyone looking to master Python programming. By now, you should have a solid grasp of how classes serve as blueprints for creating objects, and how objects are instances that encapsulate both data and functions. Embracing these concepts can significantly streamline your coding tasks and elevate your projects.

Python Classes and Objects – FAQs

What are classes and objects in Python?

  • Classes in Python are blueprints for creating objects. They define the attributes (data) and methods (functions) that objects of the class will have.
  • Objects are instances of classes. They are created from the class blueprint and can have their own unique data while sharing common methods defined in the class.

What is Python class type?

In Python, a class type refers to the type of object that a class creates. It defines the structure and behavior of objects instantiated from that class.

Why use classes in Python?

Classes in Python provide a way to structure and organize code into reusable components. They facilitate code reusability, modularity, and maintainability by encapsulating data (attributes) and functionality (methods) within objects.

How to define a class in Python?

To define a class in Python, use the class keyword followed by the class name and a colon (:). Inside the class block, define attributes and methods.

class MyClass:
    def __init__(self, arg1, arg2):
        self.arg1 = arg1
        self.arg2 = arg2
    def some_method(self):
        # Method definition
        pass

What is an object in OOP?

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.

Why do we need classes and objects?

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.



Previous Article
Next Article

Similar Reads

Reading Python File-Like Objects from C | Python
Writing C extension code that consumes data from any Python file-like object (e.g., normal files, StringIO objects, etc.). read() method has to be repeatedly invoke to consume data on a file-like object and take steps to properly decode the resulting data. Given below is a C extension function that merely consumes all of the data on a file-like obj
3 min read
Data Classes in Python | Set 6 (interconversion to and from other datatypes)
Prerequisite: Data Classes in Python | Set 5 In the last post of DataClass series, we will discuss how to get values of a DataClass object into a dictionary or tuple pairs and how to create a DataClass in a different way - from values, instead of defining it directly. asdict() function - dataclasses.asdict(instance, *, dict_factory=dict) One can si
2 min read
Comparing Old-Style and New-Style Classes in Python
In Python, the difference between old-style and new-style classes is based on the inheritance from the built-in object class. This distinction was introduced in Python 2.x and was fully adopted in Python 3.x, where all classes are new-style classes. In this article, we will see the difference between the old-style and new-style classes in Python. P
4 min read
Draw a rectangular shape and extract objects using Python's OpenCV
OpenCV is an open-source computer vision and machine learning software library. Various image processing operations such as manipulating images and applying tons of filters can be done with the help of it. It is broadly used in Object detection, Face Detection, and other Image processing tasks. Let's see how to draw rectangular shape on image and e
4 min read
Working with Datetime Objects and Timezones in Python
In this article, we are going to work with Datetime objects and learn about their behavior when Time zones are introduced. We are going to be working with the Python datetime module. Getting a Datetime objectMethod 1: Using now() method A very easy way to get a Datetime object is to use the datetime.now() method. A DateTime object is an instance/ob
5 min read
Python: Difference between Lock and Rlock objects
A thread is an entity within a process that can be scheduled for execution. Also, it is the smallest unit of processing that can be performed in an OS (Operating System). In simple words, a thread is a sequence of such instructions within a program that can be executed independently of other codes. For simplicity, you can assume that a thread is si
5 min read
Encoding and Decoding Custom Objects in Python-JSON
JSON as we know stands for JavaScript Object Notation. It is a lightweight data-interchange format and has become the most popular medium of exchanging data over the web. The reason behind its popularity is that it is both human-readable and easy for machines to parse and generate. Also, it's the most widely used format for the REST APIs. Note: For
5 min read
Addition and Subtraction on TimeDelta objects using Pandas - Python
TimeDelta module is used to represent the time in the pandas module and can be used in various ways. Performing operations like addition and subtraction are very important for every language but performing these tasks on dates and time can be very valuable. Operations on TimeDelta dataframe or series - 1) Addition - df['Result'] = df['TimeDelta1']
2 min read
How to get the list of all initialized objects and function definitions alive in Python?
In this article, we are going to get the list of all initialized objects and function definitions that are alive in Python, so we are getting all those initialized objects details by using gc module we can get the details. GC stands for garbage collector which is issued to manage the objects in the memory, so from that module, we are using the get_
2 min read
Data Classes in Python | An Introduction
dataclass module is introduced in Python 3.7 as a utility tool to make structured classes specially for storing data. These classes hold certain properties and functions to deal specifically with the data and its representation.DataClasses in widely used Python3.6 Although the module was introduced in Python3.7, one can also use it in Python3.6 by
3 min read
Data Classes in Python | Set 2 (Decorator Parameters)
Prerequisite: Data Classes in Python | Set 1 In this post, we will discuss how to modify the default constructor which dataclass module virtually makes for us. dataclass() decorator - @dataclasses.dataclass(*, init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False) By changing the values of these parameters, we can modify the b
4 min read
Data Classes in Python | Set 3 (dataclass fields)
Prerequisite: Data Classes in Python Set 1 | Set 2 In this post we will discuss how to modify certain properties of the attributes of DataClass object, without explicitly writing code for it using field function. field() function - dataclasses.field(*, default=MISSING, default_factory=MISSING, repr=True, hash=None, init=True, compare=True, metadata
4 min read
Data Classes in Python | Set 4 (Inheritance)
Prerequisites: Inheritance In Python, Data Classes in Python | Set 3 In this post, we will discuss how DataClasses behave when inherited. Though they make their own constructors, DataClasses behave pretty much the same way as normal classes do when inherited. from dataclasses import dataclass @dataclass class Article: title: str content: str author
2 min read
Data Classes in Python | Set 5 (post-init)
Prerequisite: Data Classes in Python | Set 4 In this post, we will discuss how to modify values of some attributes during object creation without coding it in __init__() by using post-init processing. __post_init__(): This function when made, is called by in-built __init__() after initialization of all the attributes of DataClass. Basically, object
2 min read
How to Dynamically Load Modules or Classes in Python
Python provides a feature to create and store classes and methods and store them for further use. The file containing these sets of methods and classes is called a module. A module can have other modules inside it. Note: For more information, refer to Python Modules Example: A simple example of importing a module is shown below in which, there are
3 min read
Create Classes Dynamically in Python
A class defines a collection of instance variables and methods to specify an object type. A class can be used to make as many object instances of the type of object as needed. An object is an identified entity with certain attributes (data members) and behaviours (member functions). Group of objects having similar characteristics and behaviour are
2 min read
The Ultimate Guide to Data Classes in Python 3.7
This article discusses data classes in Python 3.7 and provides an introductory guide for data classes in Python 3.7 and above. Data Class is a new concept introduced in Python 3.7 version. You can use data classes not only as a knowledge container but also to write boiler-plate code for you and simplify the process of creating classes since it come
4 min read
SQLAlchemy - Mapping Python Classes
SQLAlchemy is a popular Python library that provides a nice API for interacting with databases. One of its key features is the ability to map Python classes to database tables, allowing you to use Python objects to represent rows in a database table. This is known as an "object-relational mapper" (ORM). Types of Mappings in Python Classes In SQLAlc
7 min read
Abstract Classes in Python
An abstract class can be considered a blueprint for other classes. It allows you to create a set of methods that must be created within any child classes built from the abstract class. A class that contains one or more abstract methods is called an abstract class. An abstract method is a method that has a declaration but does not have an implementa
8 min read
Why do Python classes inherit object?
In Python, every class you create inherits from a special class known as an object. This foundational element simplifies and empowers Python programming. When a new class is defined without specifying a superclass, Python assumes that it inherits from the object class. This is referred to as a "new-style" class declaration and was introduced in Pyt
3 min read
Python Tkinter | Moving objects using Canvas.move() method
The Canvas class of Tkinter supports functions that are used to move objects from one position to another in any canvas or Tkinter top-level. Syntax: Canvas.move(canvas_object, x, y)Parameters: canvas_object is any valid image or drawing created with the help of Canvas class. To know how to create object using Canvas class take reference of this. x
2 min read
Python | Unit Test Objects Patching | Set-1
The problem is writing unit tests and need to apply patches to selected objects in order to make assertions about how they were used in the test (e.g., assertions about being called with certain parameters, access to selected attributes, etc.). To do so, the unittest.mock.patch() function can be used to help with this problem. It’s a little unusual
2 min read
Python | Unit Test Objects Patching | Set-2
MagicMock instances that are normally used as replacement values are meant to mimic callables and instances. They record information about usage and allow to make assertions as shown in the code given below - Code #6: from unittest.mock import MagicMock m = MagicMock(return_value = 10) print(m(1, 2, debug = True), "\n") m.assert_called_wi
2 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 it for maintaining its state. Class instances can
2 min read
Print objects of a class in Python
An Object is an instance of a Class. A class is like a blueprint while an instance is a copy of the class with actual values. When an object of a class is created, the class is said to be instantiated. All the instances share the attributes and the behavior of the class. But the values of those attributes, i.e. the state are unique for each object.
2 min read
Flattening JSON objects in Python
JSON(JavaScript Object Notation) is a data-interchange format that is human-readable text and is used to transmit data, especially between web applications and servers. The JSON files will be like nested dictionaries in Python. To convert a text file into JSON, there is a json module in Python. This module comes in-built with Python standard module
3 min read
Session Objects - Python requests
Session object allows one to persist certain parameters across requests. It also persists cookies across all requests made from the Session instance and will use urllib3’s connection pooling. So, if several requests are being made to the same host, the underlying TCP connection will be reused, which can result in a significant performance increase.
2 min read
Built-in Objects in Python-builtins
This Python module provides direct access to all 'built-in' identifiers of Python. For example, builtins.open is the full name for the built-in function open(). This module is not normally accessed explicitly by most applications, but can be useful in modules that provide objects with the same name as a built-in value, but in which the built-in of
3 min read
Detecting objects of similar color in Python using OpenCV
OpenCV is a library of programming functions mainly aimed at real-time computer vision. In this article, we will see how to get the objects of the same color in an image. We can select a color by slide bar which is created by the cv2 command cv2.createTrackbar. Libraries needed:OpenCV NumpyApproach: First of all, we need to read the image which is
3 min read
Creating nested dataclass objects in Python
Dataclasses is an inbuilt Python module which contains decorators and functions for automatically adding special methods like __init__() and __repr__() to user-defined classes. Dataclass Object is an object built into the Dataclasses module. This function is used as a decorator to add special methods directly to a user-defined class. This decorator
3 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg