Which is better in python, del or delattr?

后端 未结 8 1893
既然无缘
既然无缘 2020-12-12 11:08

This may be silly, but it\'s been nagging the back of my brain for a while.

Python gives us two built-in ways to delete attributes from objects, the del

相关标签:
8条回答
  • 2020-12-12 11:42

    Not sure about the inner workings, but from a code reusability and don't be a jerk coworker perspective, use del. It's more clear and understood by people coming from other languages as well.

    0 讨论(0)
  • 2020-12-12 11:44
    • del is more explicit and efficient;
    • delattr allows dynamic attribute deleting.

    Consider the following examples:

    for name in ATTRIBUTES:
        delattr(obj, name)
    

    or:

    def _cleanup(self, name):
        """Do cleanup for an attribute"""
        value = getattr(self, name)
        self._pre_cleanup(name, value)
        delattr(self, name)
        self._post_cleanup(name, value)
    

    You can't do it with del.

    0 讨论(0)
提交回复
热议问题