|Programmer's Python - Default Methods|
|Written by Mike James|
|Monday, 06 July 2020|
Page 2 of 2
Custom Deleting Attributes
Setting and getting an attribute aren’t the only things you can customize.
You can also set up a custom delete.
There are two standard ways to delete an attribute.
You can use:
This is efficient but can only be used if you know the object and attribute ahead of time i.e. it is not dynamic.
If this isn’t the case then you can use the:
function. The difference is that it is slower and the attribute is specified as a string giving its name.
In either case the magic method __delattr__ is called if it is defined in the class for an instance or in the metaclass for a class object.
class MyClass(metaclass=MyMeta): myAttribute1=42 def __delattr__(self, item): print("delete called")
You will see the message “delete called” in response to either way of deleting an attribute:
myObj=MyClass() del myObj.myAttribute1 delattr(myObj,"myAttribute1")
Notice that this is slightly different from the other magic methods in that the class to use to call the method is determined by del or delattr which are not class attributes. However, there is the same potential for infinite recursion if you use del or delattr in __delattr__.
def __delattr__(self, item): print("delete called") delattr(self,item)
results in an infinite recursion.
The proper way to do the job is to call the superclass’s __delattr__:
class MyClass(metaclass=MyMeta): myAttribute1=42 def __delattr__(self, item): print("delete called") super().__delattr__(item)
The dir function will return a list of names of the attributes of an object. You can override the default behavior by defining the __dir__ function. All that __dir__ has to do is return a list or more generally a sequence e.g. tuple, str, etc.. The list is then passed back to dir which sorts it before returning it to the caller.
As always, defining __dir__ in a class overrides the dir operation in any instance of the class, but not the class object, and defining it in the metaclass overrides it for the class object.
class MyClass(metaclass=MyMeta): def __dir__(self): return ['C', 'A', 'B']
returns a list of strings which have nothing at all to do with the local variables. If you use:
you will see:
['A', 'B', 'C']
The dir function has sorted the list as promised. It is tempting to use the __dir__ function to do things that have nothing to do with local variables, but this isn’t a generally a good idea because it will confuse any programmer who knows what dir is supposed to do.
By default dir uses the instance and the class __dict__ to discover what attributes have been defined.
Notice that this could be wrong if you have defined a __getattr__ or __getattribute__ function.
In chapter but not in this extract:
|Last Updated ( Monday, 06 July 2020 )|