In this Page, We are Providing Python Programming – Customizing Attribute Access. Students can visit for more Detail and Explanation of Python Handwritten Notes Pdf.
Python Programming – Customizing Attribute Access
Customizing attribute access
The following are some methods that can be defined to customize the meaning of attribute access for class instance.
object.___getattr____ ( self , name )
Called when an attribute lookup does not find the attribute name. This method should return the (computed) attribute value or raise an AttributeError exception. Note that, if the attribute is found through the normal mechanism, ___getattr___ ( ) is not called.
>>> class HiddenMembers: . . . def ___getattr___ ( self , name ) : . . . return "You don't get to see "+name . . . >>> h=HiddenMembers ( ) >>> h . anything " You don't get to see anything "
- Python Data Persistence – property () Function
- Python Interview Questions on Classes and Inheritance
- Python Program to Form a Dictionary from an Object of a Class
object . setattr ( self , name , value )
Called when an attribute assignment is attempted. The name is the attribute name and value is the value to be assigned to if. Each class, of course, comes with a default ___setattr___ , which simply set the value of the variable, but that can be overridden.
>>> class Unchangable: . . . def ___setattr____ ( self , name , value ) : . . . print " Nice try " . . . >>> u=Unchangable ( ) >>> u . x=9 Nice try >>> u . x Traceback ( most recent call last ) : File "<stdin>", line 1, in ? AttributeError: Unchangable instance has no attribute 'x' ;
object.___delattr___ ( self , name )
Like ____setattr___ ( ), but for attribute deletion instead of assignment. This should only be implemented if del ob j . name is meaningful for the object.
>>> Class Permanent : . . . def ___delattr____ ( self , name ) : . . . print name , " cannot be deleted " . . . >>> p=Permanent ( ) >>> p . x=9 >>> del p . x x cannot be deleted >>> p . x 9