constructor in class in python by R4R Team

__init__() is the function which work as a constructor when we build any class.

Syntax-

def __init__(self,variables):
body


program-

#create class
class Computer():
def __init__(self):
print("Object is created")

#create object
c1=Computer()
c2=Computer()


output-

Object is created
Object is created


-In this program, initially we create a class named as 'Computer' that contain constructor named as __init__()
-So when we create an object by c1=Computer() then this function automatically call and print 'Object is created' and similarly other object works.

Pass argument in constructor-

program-

#create class
class Computer():
def __init__(self,name,age):
print("Name is ",name)
print("Age is ",age)

#create object
c1=Computer('John wick',89)
c2=Computer('Tony strak',45)


output-

Name is John wick
Age is 89
Name is Tony strak
Age is 45




Leave a Comment:
Search
Categories
R4R Team
R4Rin Top Tutorials are Core Java,Hibernate ,Spring,Sturts.The content on R4R.in website is done by expert team not only with the help of books but along with the strong professional knowledge in all context like coding,designing, marketing,etc!