Python Classes and Objects
In this tutorial you will learn, how to create classes and objects in Python.
Python is an object-oriented programming language. This means a Python programmer is able to take advantages of all pillars(Polymorphism, Inheritance, Abstraction, Encapsulation) of object oriented paradigm. The model of Object-Oriented Programming (OOP) is based on the concept of classes and objects.
Create a Simple Class
The class keyword allows you to create a new class.
class Employee: name = "John" age = 26
Create Class Object
Creating an object of a class is a simple matter of typing the class name, followed by a pair of parentheses.
class Employee: name = "John" age = 26 e = Employee() print(e.name, e.age) print(type(e)) # <class '__main__.Employee'>
John 26 <class '__main__.Employee'>
Initializing the Object
The __init__() method is commonly known as an initializer method because it initializes the object's data attributes.
An object of a class usually initialized by implementing the __init__() method. When an object is created, Python first creates an empty object and then calls the __init__() method for that new object.
class Employee: def __init__(self, name, age): self.name = name self.age = age e = Employee("Sam", 36) print(e.name, e.age)
Sam 36
Object Method
A method is formatted identically to a function. It starts with the def keyword, followed by a space, and the name of the method. Methods work in exactly the same way as simple functions, with one crucial exception: a method's first argument always receives the instance object. Those methods that do not take any arguments have at least the argument as self.
class Employee: def __init__(self, name, age): self.name = name self.age = age def details(self): print("Employee Name:", self.name) print("Employee Age:", self.age) emp = Employee("Sam", 36) emp.details()
Employee Name: Sam Employee Age: 36
Self Parameter
The argument self is usually used to refer to object itself. When a method is called, Python makes the self parameter reference the specific object that the method is supposed to operate on.
class Employee: def __init__(selfemployee, name, age): selfemployee.name = name selfemployee.age = age def details(selfemployee): print("Employee Name:", selfemployee.name) print("Employee Age:", selfemployee.age) emp = Employee("Sam", 36) emp.details()
Employee Name: Sam Employee Age: 36
Delete Object and Property
The del keyword allows to delete object or object property followed by object name.
class Employee: def __init__(self, name, age): self.name = name self.age = age emp1 = Employee("Sam", 36) emp2 = Employee("Mark", 28) del emp1.name # Deleted object's property del emp2 # Object deleted
Empty Class
The pass keyword allows to create empty class for data storage.
class PermanentEmployee: pass emp = PermanentEmployee() emp.name = "Sam" emp.age = 10