class Dog(): # definition of the class ("blueprint")
# indentation starts - "inside of class"
def eat(self): # a method (NOTICE THAT IT IS INSIDE THE CLASS DEFINITION)
pass # using "pass" to write it as an empty function (to be filled later)
def sleep(self):
pass
def sit(self):
pass
# main code chunk! (outside of class definition now)
= Dog() # creates an instance of type "Dog"
a = 'Pug' # its breed (attribute) is 'Pug"
a.breed = Dog()
b = 'Boxer' b.breed
Object-Oriented Programming
- Originally, computers were designed for just running algorithms for performing specific tasks.
- With the invention of operating systems, databases and graphical user interfaces, however, programming took a turn toward representing objects virtually and interacting with them.
- For achieving that, we needed a new way of articulating programming and programming languages: the Object-Oriented Paradigm.
Classes and objects
- We define classes, which are basically “blueprints” for the objects (or, you could say, type definitions)
- We instantiate an object of some class by just writing the class name with parenthesis - like
Dog()
- We instantiate an object of some class by just writing the class name with parenthesis - like
- These classes define attributes (variables) and methods (functions) for an object of its type.
Example: the Turtle class
- Remember the turtles we are using to draw? They are also objects of class Turtle.
import turtle
= turtle.Turtle() # creates a turtle
raphael = turtle.Turtle() # creates another turtle
leonardo print(raphael.pos) # gets the attribute "position" of the turtle Raphael
100) # calls the method "forward" for the turtle Leonardo leonardo.forward(
Some principles and rules
- PEP-8 style guidelines require that we write the names of classes starting with capital letters! (e.g.,
Dog
,Car
,Player
, etc.).- This helps A LOT differentiating them from functions (like
eat()
,sleep()
, etc.) and variables (likea
,b
, etc.).
- This helps A LOT differentiating them from functions (like
- The Single Responsibility Principle states that every class should have one and only one responsibility. All class attributes and methods should be aligned with that one responsibility.
- This helps organize classes and makes changes easier.
- As a class grows, it may need to be split (a process that is part of what we call refactoring).