Question

I'm trying to figure out what I would use the object() built-in function for. It takes no arguments, and returns a "featureless object" of the type that is common to all Python classes, and has all the methods that are common to all Python classes.

To quote Jack Skellington, WHAT. IS. THIS?

Était-ce utile?

La solution

Even if you do not need to program with it, object serves a purpose: it is the common class from which all other objects are derived. It is the last class listed by the mro (method resolution order) method. We need a name and object for this concept, and object serves this purpose.

Another use for object is to create sentinels.

sentinel = object()

This is often used in multithreaded programming -- passed through queues -- to signal a termination event. We might not want to send None or any other value since the queue handler may need to interpret those values as arguments to be processed. We need some unique value that no other part of the program may generate.

Creating a sentinel this way provides just such a unique object that is sure not to be a normal queue value, and thus can be tested for and used as a signal for some special event. There are other possibilities, such as creating a class, or class instance, or a function, but all those alternatives are bigger, more resource heavy, and not as pithy as object().

Autres conseils

It is most useful if you are overriding the dot (especially __setattr__), it allows you to break recursion. For example:

class SomeClass(object):
    def __setattr__(self, name, value):
        if name not in ('attr1', 'attr2', 'attr3', 'attr4'):
            object.__setattr__(self, name, value)
        else:
            do_something_else()
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top