Home > Blockchain >  how to create a python object where every attribute is None
how to create a python object where every attribute is None

Time:03-17

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

CodePudding user response:

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

CodePudding user response:

No sure if I understood your question (not very good at english), but i think you could try using hasattr (https://docs.python.org/3/library/functions.html#hasattr) to check if the attribute exist and return wathever you want if it doesnt

CodePudding user response:

In case you still want the class to return actual attributes when they do exist, you could have __getattribute__ catch attribute errors:

class MyObject(object):
    def __getattribute__(self, name):
        try:
            return object.__getattribute__(self, name)
        except AttributeError:
            return None

CodePudding user response:

I would imagine that if the attribute does actually exist that you'd want its value, therefore I propose:

class MyClass:
    def __init__(self):
        self.a = 1
    def __getattr__(self, name):
        try:
            return super(MyClass, self).__getattr__(name)
        except AttributeError:
            pass
        return None

mc = MyClass()

print(mc.a)
print(mc.b)

Output:

1
None
  • Related