Box Making Class

Example of basic Class

Class features used in this example

Simple box making example

    class MakeBox:
        def __init__(self, length, width, height, density):
            self.length = length
            self.width = width
            self.height = height
            self.density = density
            self.reCalc()

        def calcVolume(self):
            self.volume = self.width * self.length * self.height

        def calcSurface(self):
            step1 = self.width * self.height * 2
            step2 = self.width * self.length * 2
            step3 = self.height * self.length * 2
            self.surface = step1 + step2 + step3

        def calcWeight(self):
            self.weight = self.volume * self.density

        def reCalc(self):
            self.calcVolume()
            self.calcSurface()
            self.calcWeight()

        # Should have a set height,width,length, density (but not for volume,surface,weight as they are derived from the first four)
        # should have a get height, width, length, density, volume, surface, weight
        # you may also want to rename the properties with an _ to let folks know NOT to access them directly

        def setHeight(self,newHeight):
            self.height = newHeight
            self.reCalc()

        def getHeight(self):
            return self.height

        def printstats(self):
            # should not be done this way in class
            print("""
            Box Height: {0}
            Box Width: {1}
            Box Length: {2}
            Box Density: {3}
            Box Volume: {4}
            Box Weight: {5}
            Box Surface Area: {6}
            """.format(self.height,self.width,self.length,self.density,self.volume,self.weight,self.surface))

        def __str__(self):
            result = """
            Box Height: {0}
            Box Width: {1}
            Box Length: {2}
            Box Density: {3}
            Box Volume: {4}
            Box Weight: {5}
            Box Surface Area: {6}
            """.format(self.height,self.width,self.length,self.density,self.volume,self.weight,self.surface)
            return result

    if __name__ == "__main__":
        # NOTE: this only runs if file is directly run
        # if it has been "imported" this section is ignored as the file is
        # no longer the "__main__" file

        newbox = MakeBox(5, 10, 2, 3.5)

        newbox.printstats()

        newbox.height = 50
        newbox.reCalc()
        newbox.printstats()

        nextbox = MakeBox(10, 10, 100, 5.5)
        nextbox.printstats()

        print(nextbox)

Page last updated on 20230911

HTML 5 Validation CSS 3 Validation Web Accessibility EValuator