python __getattr__ geeksforgeeks 1

python __getattr__ geeksforgeeks

class Foo(object):
    def __init__(self):
        self.bar = "bar attribute"

    def __getattr__(self, attr):
        return attr.upper()

foo = Foo()
print(foo.bar)	# Output: bar attribute
print(foo.another_no_exist_attribute) # Output: ANOTHER_NO_EXIST_ATTRIBUTE
print(foo.itworks) # Output: ITWORKS

Here is what the above code is Doing:
1. When we try to access an attribute that doesn’t exist, Python will call the __getattr__ method.
2. The __getattr__ method will return the attribute name in uppercase.
3. If the attribute exists, Python will return the value of the attribute.

Similar Posts