__init__ and __str__ Method in Python

Master Python with 70+ Hands-on Projects and Get Job-ready - Learn Python

Program 1

# init() and str() method
# class Test:
#     def __init__(self):
#         print("Hello i am init method ")

#     def display(self):
#             print("Hello i am method method ")
#calling
# T1=Test()
# T2=Test()
# T3=Test()
# T4=Test()
#T1.display()



# class MyClass:
#     def __init__(self,a,b):
#         self.a=a
#         self.b=b

#     def add(self):
#         return(self.a+self.b)
#     def sub(self):
#         return(self.a-self.b)        
#     def multi(self):
#         return(self.a*self.b)        
#     def division(self):
#         return(self.a//self.b)        

# #calling
# x=int(input("Enter First Number"))
# y=int(input("Enter Second Number"))
# M=MyClass(x,y)     
# print(M.add())
# print(M.sub())
# print(M.multi())
# print(M.division())

# str method
# class Test:
#     def __init__(self):
#         print("Hello i am init")
#     def __str__(self):
#                 return("Hello i am str method")

# #Calling

# T=Test()
# print(T)

Program 2

# Classes and Object in Python
# class Test:
#     def display(self):
#         self.n=1000  #Instance variable
#         n=100 #Local variable
#         print("Local: ",n)
#         print("Instance: ",self.n)
#     def show(self):
#         n=500 #Local variable
#         print("Local: ",n)
#         print("Instance: ",self.n)

# #Calling 
# T=Test()
# T.display()
# T.show()
# print("Calling place: ",T.n)

# Second Example
# class Test:
#     def getdata(self):
#         self.n=10
#     def increment(self):
#         self.n+=1

# #calling
# T1=Test()
# T2=Test()
# T1.getdata()  # T1.n=13
# T2.getdata()   # T2.n=10
# T1.increment()
# T1.increment()
# T1.increment()
# print(T1.n)
# print(T2.n)
# print(id(T1))
# print(id(T2))

# Student Example
class Student:
    def getdata(self,rno,name,per):
        self.rno=rno
        self.name=name
        self.per=per
    def display(self):
        print("Roll No: ",self.rno)        
        print("Name: ",self.name)
        print("Percentage : ",self.per)        

#Calling 
S1=Student()
S2=Student()
S1.getdata(101,"Vivek",98.45)
S2.getdata(102,"Amit",92.45)
S1.display()
S2.display()

 

We work very hard to provide you quality material
Could you take 15 seconds and share your happy experience on Google

courses

DataFlair Team

DataFlair Team provides high-impact content on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. We make complex concepts easy to grasp, helping learners of all levels succeed in their tech careers.

Leave a Reply

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