I’ve spent all of last week trying to wrap my mind around Object Oriented Programming in general and in Python specifically and here are my notes:
Everything in Python is an Object! Strings are objects, Dictionaries are objects, Lists are objects, Integers are objects…get the picture?
Objects: are copies of classes which contain attributes and methods.
Classes: a blueprint of a thing; it’s used by following its directions to build a thing; it can be used to make one thing or thousands of things. Takes a hard/complicated problem and breaks it up into smaller pieces that hide their complexity from the rest of the program
Attributes/variable: assignment; describes the thing
Methods/function: code; defines what the thing can do; the things behavior
self: an alias to the instance/object; a temporary placeholder; points to the specific object
__init__: constructor; defines the state of a thing when it gets created; automatically calls the classes’ predefined __init__ methods at creation
Object/Instance: a bit of self-contained code and data; is the thing that is created by following the instructions from the blueprint
Inheritance: an object that is created to take on the characteristics and functionality of another class while adding object specific characteristics and functionality; a child may inherit their father’s eye color yet the child also is a unique person, with its own characteristics and functionality and is not its father.
class Person(object): def create_name(self, name): #once the objects are created, self is replaced with person1 or person2. name is replaced Sam or Harry self.name = name #sets the objects first or second to the name Sam or Harry def display_name(self): return self.name #returns either Sam or Harry def saying(self): print 'Hello, %s' % self.name #prints Hello, Sam or Harry person1 = Person() #creates a person1 object person2 = Person() #creates a person2 object person1.create_name('Sam') #sets the person1 object's name to Sam person2.create_name('Harry') #sets the person2 object's name to Harry person1.display_name() #returns Sam person1.saying() #prints Hello, Sam
class DeathMatch(object): def __init__(self): self.lives = 3 print 'I have %s lives to start with' % self.lives number_of_lives = DeathMatch() #starts the player with 3 lives without having to take an additional step to call the function
class Father(object): eyes = "blue" height = "6\'3\"" class Daughter(Father): # Daughter inherits all the attributes of the Father class height = "5\'6\"" #Daughter's height will override the inherited Father's height sarah = Daughter() print sarah.eyes print sarah.height
- Learn Python the Hard Way by Zed Shaw
- Learn to Program and Analyze Data with Python by Charles Severance