class test(object):
def __init__(self, a = 0):
test.a = a
t = test()
print test.a ## obviously we get 0
''' ====== Question ====== '''
print test.somethingelse ## I want if attributes not exist, return None. How to do that?
First of all, you are adding the variable to the class test.a = a
. You should be adding it to the instance, self.a = a
. Because, when you add a value to the class, all the instances will share the data.
You can use __getattr__
function like this
class test(object):
def __init__(self, a = 0):
self.a = a
def __getattr__(self, item):
return None
t = test()
print t.a
print t.somethingelse
Quoting from the __getattr__
docs,
Called when an attribute lookup has not found the attribute in the usual places (i.e. it is not an instance attribute nor is it found in the class tree for self). name is the attribute name.
Note: The advantage of __getattr__
over __getattribute__
is that, __getattribute__
will be called always, we have to handle manually even if the current object has the attribute. But, __getattr__
will not be called if the attribute is found in the hierarchy.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With