• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
PythonForBeginners.com

PythonForBeginners.com

Learn By Example

  • Home
  • Learn Python
    • Python Tutorial
  • Categories
    • Basics
    • Lists
    • Dictionary
    • Code Snippets
    • Comments
    • Modules
    • API
    • Beautiful Soup
    • Cheatsheet
    • Games
    • Loops
  • Python Courses
    • Python 3 For Beginners
You are here: Home / Basics / Classes in Python

Classes in Python

Author: Aditya Raj
Last Updated: August 5, 2021

If you are a beginner in python programming, you must be knowing about primitive data types like integers, floating point numbers, strings and complex numbers. Also, you might have learnt about in built data structures like python dictionary, list, tuple and set. In this article, we will learn to create complex data types to store information about real world objects using classes in python.

What are classes in Python?

As we know that python is an object oriented programming language, we can create objects to represent real world objects in python. 

An object in python is a collection of attributes which identifies the real world objects.

For example, if we try to depict a cuboid as an object in python, we will specify the value of length, breadth and height of the cuboid and will define its properties such as surface area,weight and volume.

To define the properties of objects as for the cuboid, we use classes. Thus, classes are blueprints for objects in python and classes determine the attributes and functionalities of an object. 

In our example of cuboid, a class will be a construct which will define the length, breadth, height, surface area, weight and volume of the object. A class defining attributes of a cuboid will be defined as follows.

class Cuboid:
    #code for defining constructor
    #codes to define methods

How to create objects using classes in Python?

Classes are just a blueprint for any object and they cannot be used in a program. To create the object defined by the class, we use the constructor of the class to instantiate the object. Due to this, an object is also called an instance of a class.

The constructor of a class is a special method defined using the keyword __init__(). The constructor defines the attributes of the object and initializes them as follows.

class Cuboid:
    def __init__(self):
        self.length=0
        self.breadth=0
        self.height=0
        self.weight=0

We can also create a constructor which takes the attribute values as input parameters and them initializes them as follows.

class Cuboid:
    def __init__(self, length, breadth, height, weight):
        self.length = length
        self.breadth = breadth
        self.height = height
        self.weight = weight

Class attributes

Attributes of objects are private to any instance of a class. Unlike this, class attributes are attributes of a class itself and they are shared by every instance of the class. 

The class attributes are declared outside all the methods and constructor just below the class header as follows.

class Cuboid:
    name = "Cuboid"

    def __init__(self, length, breadth, height, weight):
        self.length = length
        self.breadth = breadth
        self.height = height
        self.weight = weight

In the above code, we have defined a class attribute “name” for the Cuboid class.

Defining Methods in a class

To define the properties and functionalities of an object, we define methods in a class. The methods are functions defined inside a class which are supposed to perform a specific task and give some output.

For Example, the methods to determine the surface area, volume and density of the cuboid from length, breadth, height and weight of the cuboid can be defined as follows. 

class Cuboid:
    name = "Cuboid"

    def __init__(self, length, breadth, height, weight):
        self.length = length
        self.breadth = breadth
        self.height = height
        self.weight = weight

    def volume(self):
        x = self.length
        y = self.breadth
        z = self.height
        v = x * y * z
        print("The volume is:", v)

    def density(self):
        x = self.length
        y = self.breadth
        z = self.height
        v = x * y * z
        d = self.weight / v
        print("Density is:", d)

    def surface_area(self):
        x = self.length
        y = self.breadth
        z = self.height
        s = 2 * (x * y + y * z + x * z)
        print("The surface area is:", s)

Having defined all the attributes and methods of a class, we can use it in our python program to instantiate an object and use them as follows.

class Cuboid:
    name = "Cuboid"

    def __init__(self, length, breadth, height, weight):
        self.length = length
        self.breadth = breadth
        self.height = height
        self.weight = weight

    def volume(self):
        x = self.length
        y = self.breadth
        z = self.height
        v = x * y * z
        print("The volume is:", v)

    def density(self):
        x = self.length
        y = self.breadth
        z = self.height
        v = x * y * z
        d = self.weight / v
        print("Density is:", d)

    def surface_area(self):
        x = self.length
        y = self.breadth
        z = self.height
        s = 2 * (x * y + y * z + x * z)
        print("The surface area is:", s)


myCuboid = Cuboid(1, 2, 4,4.5)
myCuboid.density()
myCuboid.surface_area()
myCuboid.volume()

Output:

Density is: 0.5625
The surface area is: 28
The volume is: 8

Conclusion

In this article, we have studied the concept of classes in python. We have also seen how to implement the constructors and methods in a class using the example of a cuboid. We can also write the programs used in this article with exception handling using python try except to make the programs more robust and handle errors in a systematic way . Stay tuned for more informative articles.

Related

Recommended Python Training

Course: Python 3 For Beginners

Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.

Enroll Now

Filed Under: Basics Author: Aditya Raj

More Python Topics

API Argv Basics Beautiful Soup bitly Cheatsheet Code Code Snippets Command Line Comments Concatenation crawler Data Structures Data Types deque Development Dictionary Dictionary Data Structure In Python Error Handling Exceptions Filehandling Files Functions Games GUI Json Lists Loops Mechanzie Modules Modules In Python Mysql OS pip Python Python On The Web Python Strings Queue Requests Scraping Scripts Split Strings System & OS urllib2

Primary Sidebar

Menu

  • Basics
  • Cheatsheet
  • Code Snippets
  • Development
  • Dictionary
  • Error Handling
  • Lists
  • Loops
  • Modules
  • Scripts
  • Strings
  • System & OS
  • Web

Get Our Free Guide To Learning Python

Most Popular Content

  • Reading and Writing Files in Python
  • Python Dictionary – How To Create Dictionaries In Python
  • How to use Split in Python
  • Python String Concatenation and Formatting
  • List Comprehensions in Python
  • How to Use sys.argv in Python?
  • How to use comments in Python
  • Try and Except in Python

Recent Posts

  • Pandas Append Row to DataFrame
  • Convert String to DataFrame in Python
  • Pandas DataFrame to List in Python
  • Solved: Dataframe Constructor Not Properly Called Error in Pandas
  • Overwrite a File in Python

Copyright © 2012–2023 · PythonForBeginners.com

  • Home
  • Contact Us
  • Privacy Policy
  • Write For Us