I'm relatively new to Python and OO so wanted to rewrite a simple Matlab code. I'm comfortable with the definitions of classes but I'm finding it a little difficult to know what the best way to define them. Most tutorials I've found give examples using animals so then it's kind of obvious. I'm not sure if I'm just using classes like I would functions. The code below compares two possible population growth models for calculating number of occupants from the floor area in a property. I've used an 'estimation_type' class and then defined the two methods as its children. I thought this would keep things nicer but in hindsight there are no methods that relate to this class so might just be unnecessary. I think it might have been better to define a general estimation class with methods representing the two options. I'd appreciate any advice on this because, like I say, I'm new to this so I'm keen to learn the best practice from the offset.

- Code: Select all
`# Rewriting simple Matlab code in Python OO framework`

import math

import array

import matplotlib

class estimation_type:

number_of_occupants = []

floor_area = []

class bounded_exponential_growth(estimation_type):

Bound = 0.0 # Maximum number of people in a property

def calculate_num_occupants(self):

for i in range(len(self.floor_area)):

k = (-1/13.9)*math.log(1-(1/self.Bound))

self.number_of_occupants = self.number_of_occupants + [self.Bound*(1-math.exp(-k*self.floor_area[i]))]

class logistic_growth(estimation_type):

Bound = 0.0 # Maximum number of people in a property

def calculate_num_occupants(self):

for i in range(len(self.floor_area)):

a = math.exp(13.9*0.05)*(self.Bound - 1)

self.number_of_occupants = self.number_of_occupants + [self.Bound/(1+(a*math.exp(-0.05*self.floor_area[i])))]

# Estimate number of occupants

estimation_exp = bounded_exponential_growth()

estimation_log = logistic_growth()

estimation_exp.Bound = estimation_log.Bound = 10.0

estimation_exp.floor_area = estimation_log.floor_area = range(10,210,10)

estimation_exp.calculate_num_occupants()

num_occ_exp = estimation_exp.number_of_occupants

estimation_log.calculate_num_occupants()

num_occ_log = estimation_log.number_of_occupants

# Plot values

import numpy as np

import pylab as pl

plot1 = pl.plot(estimation_exp.floor_area, num_occ_exp)

plot2 = pl.plot(estimation_log.floor_area, num_occ_log)

pl.xlabel("Floor area ($m^2$)")

pl.ylabel("Number of occupants")

pl.title("Estimating number of occupants from floor area of property")

pl.legend([plot1[0], plot2[0]], ["Bounded exponential growth", "Logistic growth"],"best")

pl.show()