Question

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?
Was it helpful?

Solution

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.

OTHER TIPS

You are looking for the __getattribute__ hook. Something like this should do what you want:

class test(object):
    def __init__(self, a = 0):
        self.a = a

    def __getattribute__(self, attr):
        try:
            return object.__getattribute__(self, attr)
        except AttributeError:
            return None
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top