Skip to content

Instantly share code, notes, and snippets.

@sanfx
Last active May 3, 2019 22:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sanfx/9960fabd116c89c0ee8ba62e8f95f644 to your computer and use it in GitHub Desktop.
Save sanfx/9960fabd116c89c0ee8ba62e8f95f644 to your computer and use it in GitHub Desktop.
callable object class and magic methods __call__, __getitem__
class BaseClass(object):
def __init__(self):
"""Initialise newly created object.
"""
super(BaseClass, self).__init__()
print "Constructor called."
def __call__(self, storage):
"""Implements function call operator.
"""
print "__call__ called with {0}".format(storage)
class Magic(BaseClass):
"""Main Magic class.
"""
def __init__(self, name, spell):
print "{0} from Magic class.".format(spell)
super(Magic, self).__init__()
self.name = name
self.spell = spell
def __getitem__(self, key):
print ("Inside `__getitem__` method!")
return getattr(self, key)
def __setitem__(self, key, value):
self.__dict__[key] = value
world = Magic("Sqincsh", "Almahor")
print world['name']
world["Enter"] = "Bob"
world("test")
print world["Enter"]
class Building(object):
def __init__(self, floors):
self._floors = [None]*floors
def __setitem__(self, floor_number, data):
self._floors[floor_number] = data
def __getitem__(self, floor_number):
return self._floors[floor_number]
building1 = Building(4) # Construct a building with 4 floors
building1[0] = 'Reception'
building1[1] = 'ABC Corp'
building1[2] = 'DEF Inc'
print( building1[2] )
#Almahor from Magic class.
#Constructor called.
#Inside `__getitem__` method!
#Sqincsh
#__call__ called with test
#Inside `__getitem__` method!
#Bob
#DEF Inc
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment