Skip to content

Instantly share code, notes, and snippets.

@math2001
Created September 23, 2018 06:42
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 math2001/95740ded3666fee5635793edce691828 to your computer and use it in GitHub Desktop.
Save math2001/95740ded3666fee5635793edce691828 to your computer and use it in GitHub Desktop.
Oriented object programmation explained
# We are going to use an analogy of building houses to understand OOP.
# A class is like the plan/design of the house. It's the theory, nothing concrete.
# Our house has different properties (such as the colour, the number of doors, etc), these are called attributes.
# Our house has different behaviours (such as starting the alarm, locking every doors, etc), these are called methods.
# An instance, however, is the real thing. From one plan, one design, one *class*, we can make as many actual houses as we like
# And we can change them. For example, one house (an instance), might have 2 doors, where as an other one might have 4 doors.
# But they still have the same plan
# In code
class House:
def __init__(self):
# __init__ is a method, but a special one.
# In Python, it's called a magic method
# It is run every time you create a new instance.
print('creating a new house!')
# self is referencing to the instance we are creating. This means that we can set the attributes in here:
self.number_of_doors = 2
self.color = 'white'
self.is_locked = False
def lock(self):
# every method has to take at least one parameter, 'self'. Everytime.
self.is_locked = True
def unlock(self):
self.is_locked = False
def change_color(self, newcolor):
self.color = newcolor
# Ok, so we have defined what the plan/design of our house was. Let's create some.
# Here's how:
# instance = Plan(arguments)
# In our case:
myhouse = House()
yourhouse = House()
print(myhouse.color) # prints white
print(yourhouse.color) # prints white
print(myhouse.is_locked) # prints false
print(yourhouse.is_locked) # prints false
myhouse.change_color('red')
print(myhouse.color) # prints 'red', because we just changed it
print(yourhouse.color) # prints 'white'! Our 2 houses are INdependent.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment