Search code examples
pythonpython-3.xdescriptor

Is the class which contain __getattribute__ a descriptor?


In python3's manual:
https://docs.python.org/3/howto/descriptor.html#definition-and-introduction
In general, a descriptor is an attribute value that has one of the methods in the descriptor protocol. Those methods are __get__(), __set__(), and __delete__(). If any of those methods are defined for an attribute, it is said to be a descriptor.

class Room:
    def __init__(self,name):
        self.name = name
    def __getattribute__(self,attr):
        return  object.__getattribute__(self,attr)
    def __setattr__(self,attr,value):
        return  object.__setattr__(self,attr,value)

__getattribute__ and __setattr__ are python's magic methods,built-in functions ,Room class use magic methods to implement __get__ and __set__,strictly speaking,is the class Room a descriptor?


Solution

  • The Room class is not a descriptor. A descriptor in Python is a class that implements at least one of the descriptor methods: __get__(), __set__(), or __delete__(). These methods define how the descriptor interacts with the attributes of the owner object.

    In the Room class, the __getattribute__() and __setattr__() methods are used to intercept attribute access and assignment operations, respectively. However, these methods alone do not make Room a descriptor. They are special methods that are called automatically for every attribute access and assignment, regardless of whether the attribute is a descriptor or not.

    To make the class Room a descriptor, you would need to implement at least one of the descriptor methods (__get__(), __set__(), or __delete__()). As it stands, the Room class in your example is simply using the magic methods to handle attribute access and assignment like a regular class, but it doesn't meet the criteria to be considered a descriptor.

    To create a descriptor, you need to define one or more of the descriptor methods mentioned earlier, typically within a separate class, and then use an instance of that class as an attribute of another class. The descriptor methods will be called when accessing, setting, or deleting that attribute of the owner object .....by google treanslate