Python Class and Objects
This topic comes under the "oops" concepts, In this, we will learn about class and objects.
What is Python Class?
In a general way, we can say that class is a blueprint from which we can create an object.
This is a general definition like when we plan to make a house we will first be creating the map, and then start to make a house, here the map is called the blueprint from which we can designing the house.
In a technical way we can say, the class is a group of methods and data, which is used for future reuse.
Basically, three elements are used in class
-
Class variables
-
Instance variables
-
methods
How to write class in python
Syntax
>>> class class_name:
statement1
.
.
statementN
Example
>>> class employee_details:
def __init__(self, first, last, sal):
self.fname=first
self.lname=last
self.sal=sal
self.email=first + '.' + last + '@codersarts.com'
emp= employee_details ('naveen','kumar',50000)
print(emp. self.email l)
What is Python Object?
An object can be used to access different attributes. It is used to create an instance of the class. An instance is an object of a class created at run-time.
In the above example, you can see “emp” is an object which is used to access the attribute of class “employee_details”.
How to create Object?
Here we are creating the object "obj" from the class "A".
>>> class A:
x = 2
obj = A()
print(obj.x)