Skip to content

Instantly share code, notes, and snippets.

@lucsmall
Created February 7, 2017 05:13
Show Gist options
  • Save lucsmall/f47125131fcff2e240930fd6fdc16088 to your computer and use it in GitHub Desktop.
Save lucsmall/f47125131fcff2e240930fd6fdc16088 to your computer and use it in GitHub Desktop.
# A class is a cookie cutter that can be used to stamp out instances
# This class models a farm (well one with animals on it, at least)
# This class inherits from "object"
class Farm(object):
def __init__(self, length, width, sheep, cattle, pigs, poultry):
self.length = length
self.width = width
self.sheep = sheep
self.cattle = cattle
self.pigs = pigs
self.poultry = poultry
# define an instance method
def sell_all_sheep(self):
self.sheep = 0
# define a second instance method
def buy_sheep(self):
self.sheep += 5
# assumes a rectangular farm
# this method is disguised to look like a property
@property
def area(self):
return self.width * self.length
@property
def total_livestock(self):
return self.sheep + self.cattle + self.pigs + self.poultry
# Create an instance of Farm
myfarm = Farm(10, 20, 4, 5, 6, 7)
# access a property
print("Number of sheep:", myfarm.sheep)
# call a method
myfarm.sell_all_sheep()
print("Number of sheep after sale:", myfarm.sheep)
# get the area of the farm - note property syntax
print("Area of the farm:", myfarm.area, "units")
# get the total livestock - note property syntax
print("Total livestock:", myfarm.total_livestock)
# call a method
myfarm.buy_sheep()
print("Number of sheep after buying some:", myfarm.sheep)
# alternative syntax, passing in instance
Farm.sell_all_sheep(myfarm)
print("Number of sheep after another sale:", myfarm.sheep)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment