what is a constructor in python

0 votes
can you give an example?
Mar 30, 2019 in Python by Waseem
• 4,540 points
8,076 views

1 answer to this question.

0 votes

Constructors are for instantiating an object.The task of constructors is to initialize the data members of the class when an object of class is created. The __init__() method is called the constructor in Python and is always called when an object is created.

class Employee:  

  1.     def __init__(self,name,id):  
  2.         self.id = id;  
  3.         self.name = name;  
  4.     def display (self):  
  5.         print("ID: %d \nName: %s"%(self.id,self.name))  
  6. emp1 = Employee("John",101)  
  7. emp2 = Employee("David",102)       
  8. emp1.display();   
  9. emp2.display();  

Output:

ID: 101 
Name: John
ID: 102 
Name: David


Hope this is helpful!

To know more join Master in Python programming course today.

Thanks!

answered Apr 1, 2019 by Tushar
• 200 points

Related Questions In Python

+1 vote
7 answers
0 votes
1 answer

What is the meaning of “int(a[::-1])” in Python?

Assumming a is a string. The Slice ...READ MORE

answered Aug 27, 2018 in Python by Priyaj
• 58,020 points
6,483 views
0 votes
1 answer

What is a “method” in Python?

It's a function which is a member ...READ MORE

answered Oct 23, 2018 in Python by SDeb
• 13,300 points
758 views
0 votes
1 answer

What is the process to kill a particular thread in python?

A multiprocessing.Process can p.terminate() In the cases where I want to ...READ MORE

answered Feb 4, 2019 in Python by charlie_brown
• 7,720 points
3,739 views
0 votes
4 answers

What is a Tuple in Python and how to use it?

Tuples  are a  Unchanging sequence of values, ...READ MORE

answered Jun 21, 2020 in Python by sahil
• 500 points
2,001 views
0 votes
1 answer

What is a dictionary in Python?

Dictionary can be understood as a key-value ...READ MORE

answered Mar 4, 2019 in Python by Priyaj
• 58,020 points
700 views
0 votes
2 answers
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 7, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 4,457 views
0 votes
1 answer
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP