Chapter 9
Chapter 9
Python Programming
Using Problem Solving Approach
Reema Thareja
Creating an object or instance of a class is known as class instantiation. From the syntax, we can see that class instantiation
uses function notation. Using the syntax, an empty object of a class is created. Thus, we see that
in Python, to create a new object, call a class as if it were a function. The syntax for accessing a class member through the class
object is
Example:
Example:
10
11
12
13
14
hasattr(obj,name): The function is used to check if an object possess the attribute or not.
getattr(obj, name[, default]): The function is used to access or get the attribute of object. Since getattr() is a built-in
function and not a method of the class, it is not called using the dot operator. Rather, it takes the object as its first
parameter. The second parameter is the name of the variable as a string, and the optional third parameter is the default
value to be returned if the attribute does not exist. If the attribute name does not exist in the object's namespace and the
default value is also not specified, then an exception will be raised. Note that, getattr(obj, 'var') is same as writing
obj.var. However, you should always try to use the latter variant.
setattr(obj,name,value): The function is used to set an attribute of the object. If attribute does not exist, then it would be
created. The first parameter of the setattr() function is the object, the second parameter is the name of the attribute and
the third is the new value for the specified attribute.
delattr(obj, name): The function deletes an attribute. Once deleted, the variable is no longer a class or object attribute.
15
16
18
19
20
21