Skip to content

Python class | Basics

  • by

Use class keywords to create user define objects in Python. Python class is a blueprint (prototype from which objects are created) for features and methods of objects.

Python is an object-oriented programming language. Everything is in Python treated as an object, including variable, function, list, tuple, dictionary, set, etc.

An object is simply a collection of data (variables) and functions that act on those data.

class ClassName:
    # Statement

Python class examples

Simple example code to create a class in Python. Use the keyword class:

Attributes are the variables that belong to a class and are always public, they can be accessed using the dot (.) operator.

class MyClass:

    var = 10

Create Object and access variables

Use the class named MyClass to create objects. An Object is an instance of a Class. You can have can create many different instances.

class MyClass:
    var = 10

test = MyClass()


Python class

Constructors in Python

All classes have a function called init(), which is always executed when the class is being initiated. Use it assigns values to object properties.

class Employee:
    def __init__(self, name, salary): = name
        self.age = salary

emp1 = Employee("John", 36000)




Class with methods

The self parameter is a reference to the current instance of the class and is used to access variables that belong to the class.

class Employee:
    def __init__(self, name, salary): = name
        self.age = salary

    def my_func(self):
        print("Name " +

emp1 = Employee("John", 36000)

Output: Name John

Do comment if you have any doubts or suggestions on this Pytho class tutorial.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

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