Callable Primer

All code is in Python 3.


In [1]:
def a_function(*args, **kwargs):
    return 'Hello DjangoCon 2015!'

In [2]:
a_function()


Out[2]:
'Hello DjangoCon 2015!'

In [3]:
lambda_function = lambda: 'Enjoying Austin?'

In [4]:
lambda_function()


Out[4]:
'Enjoying Austin?'

In [5]:
class FirstClass:
    an_attribute = 'Have you visited any good restaurants?'

    def a_method(*args, **kwargs):
        self = args[0]
        return self.an_attribute

In [6]:
fc_obj = FirstClass()
fc_obj.a_method()


Out[6]:
'Have you visited any good restaurants?'

In [7]:
class SecondClass(FirstClass):

    def __init__(self):
        """Dunder/Magic method to initialize a class"""
        self.an_attribute = "Easy Tiger, La Condessa and Lambert's are my favorites."

In [8]:
sc_obj = SecondClass()
sc_obj.a_method()


Out[8]:
"Easy Tiger, La Condessa and Lambert's are my favorites."

In [9]:
class ThirdClass(SecondClass):

    def __call__(*args, **kwargs):
        """Dunder/Magic method to make object callable"""
        return "I like grabbing ice cream at Amy's, too."

In [10]:
tc_obj = ThirdClass()
tc_obj()


Out[10]:
"I like grabbing ice cream at Amy's, too."

In [11]:
# callable is a Python built-in
callable(a_function)


Out[11]:
True

In [12]:
callable(lambda_function)


Out[12]:
True

In [13]:
callable(FirstClass)


Out[13]:
True

In [14]:
callable(fc_obj)


Out[14]:
False

In [15]:
callable(sc_obj)


Out[15]:
False

In [16]:
callable(tc_obj)


Out[16]:
True