pythonooppython-object

how to create a python object where every attribute is None


I'm not sure if this can be done, but I would like an object where you can query any attribute, and it just returns None, instead of an error.

eg.

>>> print(MyObject.whatever)
None
>>> print(MyObject.abc)
None
>>> print(MyObject.thisisarandomphrase)
None

without manually assigning all of these values in the object's __init__ function


Solution

  • You can define __getattribute__:

    class MyObject:
        def __getattribute__(self, name):
            return None  # or simply return
        
    x = MyObject()
    print(x.abc)
    print(x.xyz)
    

    output:

    None
    None
    

    NB. note that is might not work with all attributes, there are reserved words, e.g. x.class