Skip to main content
Python Class With Methods and Variables

Python Classes Tutorials with Example

The Class is a blueprint for creating an object. You can combine data(attributes) and functionality(methods) together using the python class. Each class instance can have attributes attached to it for maintaining its state, also has methods for modifying its state.

What’s class in python

Classes are used to create user-defined data structures. Classes define variables called attributes and functions called methods, which identify the behaviors and actions that an object created from the class can perform with its data.

In this tutorial, we’ll create an Employee class that stores some information about the characteristics and behaviors that an individual employee can have (Like name, age, salary).

The syntax of class :

Class Employee:
	#methods
	#data
	pass

The python class definitions start with the class keyword, which is followed by the name of the class and a colon. The class attributes may be data or method. Methods of an object are corresponding functions of that class.

Those methods which are starting with __ is class constructor in OO Programming. This special function gets called whenever a new object of that class is instantiated.

Let’s define __init_ method inside the class to set the initial values of attributes:

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

The __init__() method that creates name, age and salary attributes:

Instantiate an Object in Python

We can create new instance using clas as follow

emp = Employee("Adam", 43, 1234)
emp1 = Employee("Rachel", 45, 3214)

We’ll create an instance that is built from a class and contains real data. You can create many instances from a single class.

We have passed the initial value to the employee classes.

How To Access Properties Using Python Instance

We can access instance properties using dot notation.

emp.name
emp1.age

Output:

Adam
45

As you can see, we have access properties of two different instances.

How To Change Instance Atribute Dynamically

We can change any class instance attributes dynamically as follows:

emp.age = 23

How To Define instance Methods in Python Class

The methods that are defined inside a class are called Instance methods. It can only be called from an instance of that class, Each instance method’s first parameter is always self.

class Employee:
    def __init__(self, name, age, salary):
        self.name = name
        self.age = age
		self.salary = salary
    # Instance method
    def description(self):
        return f"{self.name} is {self.age} years old and salary is {self.salary}"

Now, We can access the instance method:

>>> emp = Employee("Adam", 43, 1234)

>>> emp.description()

Output:

Adam is 43 years old and salary is 1234

Leave a Reply

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