beginnersbook.com

  • Home
  • All Tutorials
    • Learn Servlet
    • Learn JSP
    • Learn JSTL
    • Learn C
    • Learn C++
    • Learn MongoDB
    • Learn XML
    • Learn Python
    • Learn Perl
    • Learn Kotlin
  • Core Java
  • OOPs
  • Collections
  • Java I/O
  • JSON
  • DBMS

How to create Class and Objects in Python

By Chaitanya Singh | Filed Under: Python Tutorial

In the previous guide, we discussed Object-oriented programming in Python. In this tutorial, we will see how to create classes and objects in Python.

Define class in Python

A class is defined using the keyword class.

Example

In this example, we are creating an empty class DemoClass. This class has no attributes and methods.

The string that we mention in the triple quotes is a docstring which is an optional string that briefly explains the purpose of the class.

class DemoClass:
    """This is my docstring, this explains brief about the class"""

# this prints the docstring of the class
print(DemoClass.__doc__)

Output:

This is my docstring, this explains brief about the class

Creating Objects of class

In this example, we have a class MyNewClass that has an attribute num and a function hello(). We are creating an object obj of the class and accessing the attribute value of object and calling the method hello() using the object.

class MyNewClass:
    """This class demonstrates the creation of objects"""

    # instance attribute
    num = 100

    # instance method
    def hello(self):
        print("Hello World!")


# creating object of MyNewClass
obj = MyNewClass()

# prints attribute value
print(obj.num)

# calling method hello()
obj.hello()

# prints docstring
print(MyNewClass.__doc__)

Output:

100
Hello World!
This class demonstrates the creation of objects
❮ PreviousNext ❯

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Python Tutorial

Introduction

  • Python Tutorial
  • Python Introduction
  • Install Python
  • PyCharm IDE Installation
  • Python in PyCharm
  • Python Comments
  • Python Variables
  • Python Keywords & Identifiers
  • Python data types

Flow Control

  • Python If
  • Python if..else
  • Python if..elif..else
  • Python Nested If
  • Python for loop
  • Python while loop
  • Python break
  • Python continue
  • Python pass

Python Functions

  • Python Functions
  • Python Recursion

Python Datatypes

  • Python Numbers
  • Python List
  • Python Strings
  • Python Tuple
  • Python Dictionary
  • Python Set

Python OOPs

  • Python OOP
  • Python Class & Object
  • Python Constructors

Python Examples

  • Python Programs

Recently Added..

  • JSON Tutorial
  • Java Regular Expressions Tutorial
  • Java Enum Tutorial
  • Java Annotations Tutorial

Copyright © 2012 – 2021 BeginnersBook . Privacy Policy . Sitemap