Python OOPs Concepts |Creating Class and Objects

Example of creating a class, declaring an object of the class and calling the methods of the class.

Creating Classes

class sample:
    roll=101
    name="Amit"
    def show(self):
        print("roll no ",self.roll)
        print("name ",self.name)

Create an Object in Python

We can create new object instances of the classes. The procedure to create an object is similar to a function call.
Let’s take an example to create a new instance object ob. We can access attributes of objects by using the object name prefix.

#object creation
s=student()

Fetching data elements and calling the member function

print(s.roll)
print(s.name)
s.show()

class sample:
    roll=101
    name="Amit"
    def show(self):
        print("roll no ",self.roll)
        print("name ",self.name)

s=sample()
s.show()

Example:1
Python program to create a class named student with attributes as roll and name. initialize the data elements and display them?
Sol:

#class creation
class student:
    roll=101
    name="Amit"
    def show(self):
        print("Student Details")
        print("roll ",self.roll)
        print("name ",self.name)
        
#object creation
s=student()
print("Fetching Data Elements")
print(s.roll)
print(s.name)
print("Calling Memeber Function")
s.show()

Output:

Fetching Data Elements
101
Amit
Calling Memeber Function
Student Details
roll  101
name  Amit
>>> 

Example:2
Python program to create a class named employee with attributes as empno, name and salary. Initialize the data elements and display them?
Sol:

#class creation
class employee:
    empno=1001
    name="Amit"
    sal=45000
    def show(self):
        print("hello how are you")
        print("empno ",self.empno)
        print("name ",self.name)
        print("salary ",self.sal)
        

#object creation
e=employee()
print("Fetching Data Elements")
print(e.empno)
print(e.name)
print(e.sal)
print("Calling Memeber Function")
e.show()

Output:

Fetching Data Elements
1001
Amit
45000
Calling Memeber Function
hello how are you
empno  1001
name  Amit
salary  45000
>>>