'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 1:[1]
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
Solution 2:[2]
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
Solution 3:[3]
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
Solution 4:[4]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | mozway |
| Solution 2 | Senpai |
| Solution 3 | Stuart |
| Solution 4 | Albert Winestein |
