# coding: utf-8 # # Objects in Python # Everything in Python is an 'object'. # # Defining custom types of objects is easy: # In[1]: class Employee: def __init__(self, name, salary): self.name = name self.salary = salary def fire(self): self.salary = 0 # * Functions within the class (type) definition are called 'methods'. # * They take an explicit `self` parameter, through which the object is passed. # * `__init__` is the 'constructor' # * Objects are created by 'calling' the type like a function. # * Arguments in this call are passed to the constructor # In[11]: joe = Employee("Joe", 100000) joe.name # In[7]: joe.salary # Let's fire Joe. # In[8]: joe.fire() # In[9]: joe.salary # ## Inheritance # Types can be based on other types by inheritance: # In[10]: class Boss(Employee): def __init__(self, name, salary, supervises): super(Boss, self).__init__(name, salary) self.supervises = supervises def fire(self): for s in self.supervises: s.fire() super(Boss, self).fire() # In[12]: joe = Employee("Joe", 100000) jack = Employee("Jack", 100000) mike = Boss("Mike", 150000, [joe, jack]) mike.salary # In[13]: joe.salary # Now what happens to Joe's salary if Mike gets fired? # In[14]: mike.fire() # In[15]: joe.salary