Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return None when attribute does not exist

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?
like image 990
MacSanhe Avatar asked Mar 20 '14 03:03

MacSanhe


1 Answers

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.

like image 140
thefourtheye Avatar answered Sep 19 '22 21:09

thefourtheye