Last active
May 3, 2019 22:15
-
-
Save sanfx/9960fabd116c89c0ee8ba62e8f95f644 to your computer and use it in GitHub Desktop.
callable object class and magic methods __call__, __getitem__
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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