InterviewSolution
| 1. |
How do you define a constructor in Python class? Can a class have overloaded constructor in Python? |
|
Answer» Python is a COMPLETELY object ORIENTED language. It has ‘class’ keyword using which a new user defined class can be created. >>> class Myclass: PassIn object oriented programming, an object of a class is initialized by automatically invoking a certain method when it is declared. In C++ and Java, a method of the same name as the class acts as a constructor. However, Python uses a special method named as __init__() as a constructor. >>> class Myclass: def __init__(SELF): PRINT ("new object initialized") >>> x=Myclass() new object initializedHere x is declared as a new object of Myclass and __init__() method is called automatically. The constructor method always has one mandatory argument carrying reference of the object that is CALLING. It is conventionally denoted by ‘self’ identifier although you are free to use any other. Instance attributes are generally initialized within the __init__() function. >>> class Myclass: def __init__(self): self.name='Mack' self.age=25 >>> x=Myclass() >>> x.name 'Mack' >>> x.age 25In addition to self, __init__() method can have other arguments using which instance attributes can be initialized by user specified data. >>> class Myclass: def __init__(self, name, age): self.name=name self.age=age >>> x=Myclass('Chris',20) >>> x.name 'Chris' >>> x.age 20However, Python class is not allowed to have overloaded constructor as in C++ or Java. Instead you can use default values to arguments of __init__() method. >>> class Myclass: def __init__(self, name='Mack', age=20): self.name=name self.age=age >>> x=Myclass() >>> x.name 'Mack' >>> x.age 20 >>> y=Myclass('Nancy', 18) >>> y.name 'Nancy' >>> y.age 18 |
|