Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PYTHON

Python Callables

# Functions and classes are both callables, but you can actually invent your own callable objects too.

# We have a class here called Person:

class Person:
    def __init__(self, name):
        self.name = name
    def __call__(self):
        print("My name is", self.name)
# Classes are callable and we call the Person class to get back an instance of that class:

>>> trey = Person("Trey")
>>> trey
<__main__.Person object at 0x7fbf9f3331c0>
# But the Person object is also callable! We can call that Person object by putting parentheses after it:

>>> trey()
My name is Trey
# This works because we've implemented a __call__ method on the Person class. Adding a __call__ method to a class makes its class instances callable.
Source by www.pythonmorsels.com #
 
PREVIOUS NEXT
Tagged: #Python #Callables
ADD COMMENT
Topic
Name
9+2 =