Passing Instance Attribute Values in Constructor
Passing Instance Attribute Values in Constructor
Constructor
• You can specify the values of instance attributes through the constructor. The following
constructor includes the name and age parameters, other than the self parameter.
• class Student:
• def __init__(self, name, age):
• self.name = name
• self.age = age
• Now, you can specify the values while creating an instance, as shown below.
• >>> std = Student('Bill',25)
• >>> std.name
• 'Bill'
• >>> std.age
• 25
• Note:
• You don't have to specify the value of the self parameter. It will be
assigned internally in Python.
• You can also set default values to the instance attributes. The
following code sets the default values of the constructor parameters.
So, if the values are not provided when creating an object, the values
will be assigned latter.
Example: Instance Attribute Default Value
• class Student:
• def __init__(self, name="Guest", age=25)
• self.name=name
• self.age=age
• Now, you can create an object with default values, as shown below.
• >>> std = Student()
• >>> std.name
• 'Guest'
• >>> std.age
• 25
Class Attributes vs Instance Attributes in Python
• The following table lists the difference between class attribute and instance
attribute:
Class Attributes vs Instance Attributes in Python
lass Attribute Instance Attribute
Defined directly inside a class. Defined inside a constructor using
the self parameter.
Shared across all objects. Specific to object.
Accessed using class name as well as Accessed using object dot notation
using object with dot notation, e.g. object.instance_attribute
e.g. classname.class_attribute or object
.class_attribute