Python allows an easy way to check whether an object contains/has an attribute or method with the specified name as follows:
1) getattr:
Gets the attribute/method with the specified name, usage as follows:
usage: getattr(obj, 'method/attribute name')
eg:
a='RK';
getattr(a, 'split')
2) hasattr:
Checks whether object has the attribute/method with the specified name, usage as follows:
usage: hasattr(obj, 'method/attribute name')
eg:
a='RK';
hasattr(a, 'split')
3) setattr:
Sets the attribute/method with the specified name, usage as follows:
usage: setattr(obj, 'method/attribute name', value)
eg:
a=Employee(23)
setattr(a, 'id', 45)
No comments:
Post a Comment