InterviewSolution
| 1. |
Explain the builtins getattr() and setattr() functions. |
|
Answer» The built-in functions MAKE it possible to retrieve the value of specified attribute of any object (getattr) and add an attribute to given object. Following is definition of a test class without any ATTRIBUTES. >>> class test: PassEvery Python class is a subclass of ‘object’ class. Hence it inherits attributes of the class which can be listed by dir() function: >>> dir(test) ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__']The setattr() function can be used to add a class LEVEL attribute to our test class. >>> setattr(test,'name','Ravi')To retrieve its value use getattr() function. >>> getattr(test,'name') 'Ravi'You can of course access the value by dot (.) notation >>> test.name 'Ravi'Similarly, these functions add/retrieve attributes to/from an object of any class. Let us declare an INSTANCE of test class and add age attribute to it. >>> x=test() >>> setattr(x,'age',21)Obviously, ‘age’ becomes the instance attribute and not class attribute. To retrieve, use getattr() or ‘.’ operator. >>> getattr(x,'age') 21 >>> x.age 21Use dir() function to verify that ‘age’ attribute is available. >>> dir(x) ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'age', 'name']Incidentally, Python also provides ‘hasattr()’ function to check if an object possesses the given attribute. >>> hasattr(x,'age') TRUE >>> hasattr(test, 'age') False |
|