Python class | Basics

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.

A 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, it 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()
print(test.var)

Output:

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):
        self.name = name
        self.age = salary


emp1 = Employee("John", 36000)

print(emp1.name)
print(emp1.age)

Output:

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):
        self.name = name
        self.age = salary

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


emp1 = Employee("John", 36000)
emp1.my_func()

Output: Name John

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

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

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


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.