Course
Constructors
Python Tutorial
This Python tutorial has been written for the beginners to help them understand the basic to advanced concepts of Python Programming Language. After completing this tutorial, you will find yourself at a great level of expertise in Python, from where you can take yourself to the next levels to become a world class Software Engineer.
Constructors
In object-oriented programming, an object of a class is characterized by one or more instance variables or attributes, whose values are unique to each object. For example, if the Employee class has an instance attribute as name. Each of its objects e1 and e2 may have different value for the name variable.
A constructor is an instance method in a class, that is automatically called whenever a new object of the class is declared. The constructor' role is to assign value to instance variables as soon as the object is declared.
Python uses a special method called
__init__()
to initialize the instance variables for the object, as soon as it is declared.The
__init__()
method acts as a constructor. It needs a mandatory argument self, which the reference to the object.def __init__(self):#initialize instance variables
The
__init__()
method as well as any instance method in a class has a mandatory parameter, self. However, you can give any name to the first parameter, not necessarily self.Let us define the constructor in Employee class to initialize name and age as instance variables. We can then access these attributes of its object.
Example
class Employee: 'Common base class for all employees' def __init__(self): self.name = "Bhavana" self.age = 24
e1 = Employee()print ("Name: {}".format(e1.name))print ("age: {}".format(e1.age))
It will produce the following output
Name: Bhavanaage: 24
Parameterized Constructor
For the above Employee class, each object we declare will have same value for its instance variables name and age. To declare objects with varying attributes instead of the default, define arguments for the
__init__()
method. (A method is nothing but a function defined inside a class.)Example
In this example, the
__init__()
constructor has two formal arguments. We declare Employee objects with different valuesclass Employee: 'Common base class for all employees' def __init__(self, name, age): self.name = name self.age = age
e1 = Employee("Bhavana", 24)e2 = Employee("Bharat", 25)
print ("Name: {}".format(e1.name))print ("age: {}".format(e1.age))print ("Name: {}".format(e2.name))print ("age: {}".format(e2.age))
It will produce the following output
Name: Bhavanaage: 24Name: Bharatage: 25
You can assign defaults to the formal arguments in the constructor so that the object can be instantiated with or without passing parameters.
class Employee: 'Common base class for all employees' def __init__(self, name="Bhavana", age=24): self.name = name self.age = age
e1 = Employee()e2 = Employee("Bharat", 25)
print ("Name: {}".format(e1.name))print ("age: {}".format(e1.age))print ("Name: {}".format(e2.name))print ("age: {}".format(e2.age))
It will produce the following output
Name: Bhavanaage: 24Name: Bharatage: 25
Python - Instance Methods
In addition to the
__init__()
constructor, there may be one or more instance methods defined in a class. A method with self as one of the formal arguments is called instance method, as it is called by a specific object.Example
In the following example a
displayEmployee()
method has been defined. It returns the name and age attributes of the Employee object that calls the method.class Employee: def __init__(self, name="Bhavana", age=24): self.name = name self.age = age def displayEmployee(self): print ("Name : ", self.name, ", age: ", self.age)
e1 = Employee()e2 = Employee("Bharat", 25)
e1.displayEmployee()e2.displayEmployee()
It will produce the following output
Name : Bhavana , age: 24Name : Bharat , age: 25
You can add, remove, or modify attributes of classes and objects at any time
emp1.salary = 7000 # Add a 'salary' attribute.emp1.name = 'xyz' # Modify 'name' attribute.del emp1.salary # Delete 'salary' attribute.
Instead of using the normal statements to access attributes, you can use the following functions −
- The getattr(obj, name[, default]) − to access the attribute of object.
- The hasattr(obj,name) − to check if an attribute exists or not.
- The setattr(obj,name,value) − to set an attribute. If attribute does not exist, then it would be created.
- The delattr(obj, name) − to delete an attribute.
print (hasattr(e1, 'salary')) # Returns true if 'salary' attribute existsprint (getattr(e1, 'name')) # Returns value of 'name' attributesetattr(e1, 'salary', 7000) # Set attribute 'salary' at 8delattr(e1, 'age') # Delete attribute 'age'
It will produce the following output
FalseBhavana
Practice with Online Editor
Note: This Python online Editor is a Python interpreter written in Rust, RustPython may not fully support all Python standard libraries and third-party libraries yet.
Remember to save code(Ctrl
+S
Or
Command
+S
) before run it.