Skip to content

Instantly share code, notes, and snippets.

@prodeveloper
Last active May 16, 2017 06:37
Show Gist options
  • Save prodeveloper/a9848f0b9712290cf0e41b19a04ed3b6 to your computer and use it in GitHub Desktop.
Save prodeveloper/a9848f0b9712290cf0e41b19a04ed3b6 to your computer and use it in GitHub Desktop.
Introduction to classes in Python

Python provides a rich set of data types and constructs to help you organize your code.

Of all of them, classes are one of the most potent.

Classes allow you to organize your code by packing related functionality and restricting operations that are possible on your data. This allows for great legibility to your code.

Let us start by looking at an example where we could write our code without using classes.

##Step 1

Let us suppose we have a requirement similar to the one that we covered in our functions class.

     As a user I want the script area_triangle.py to first ask me for a base and height and then give me an area

The most obvious way to implement this code would be to just write it as a function.

def area_triangle(base,height):
    int_base = int(base)
    int_height = int(height)
    area = 0.5 * int_base * int_height
    return area
base = input("What is the base of your triangle?:")
height = input ("What is the height of your triangle?:")
area = area_triangle(base,height)
print(area)

This code will work but unfortunately it does not convey much information about what we are trying to do.

##Step 2

Let us now see how we would make this work using classes. Let us start by creating the necessary project folder.

The requirement we are now going to implement is as follows

    As a user I want the script rectangle.py to first ask me for the base then the height and give me the area
mkdir 10lesson
cd 10lesson
touch rectangle.py

Inside the rectangle.py file, we can now type in our code as

class Rectangle():
    def area(self,base,height):
        int_base = int(base)
        int_height = int(height)
        area = int_base * int_height
        return area
base = input("What is the base of your rectangle?:")
height = input ("What is the height of your rectangle?:")
rectangle = Rectangle()
area = rectangle.area(base,height)
print(area)

Now run the code.

Some of the key areas to focus on are that

  • Class methods should start with the self keyword
  • You must define the class before you can use it
  • You access class methods via object notation

##Step 3

In the step above, we were able to show that you can make your code a bit more neater just by putting it into a class.

Suppose you now want to tighten your class a bit more. We can see that clearly length and base are properties of the rectangle and not necessarily tied to the area of it. Let us reflect this in our code by setting the variables when initiating the code.

Going back to your rectangle.py file. Modify it so that now it looks like this.

class Rectangle():
    def __init__(self,base,height):
        self.base=int(base)
        self.height = int(height)
        
    def area(self):
        return self.height * self.base
        
base = input("What is the base of your rectangle?:")
height = input ("What is the height of your rectangle?:")
rectangle = Rectangle(base,height)
area = rectangle.area()
print(area)

Now run the code.

You note that not only is the code neater, we now have more centralized way of handling the data.

Now let's suppose the client has changed their requirements a bit and it now looks like this.

    As a user I want the script rectangle.py to first ask me for the base then the height and give me the area and the perimeter

To implement the code above, we only need add one extra method to the class as follows

class Rectangle():
    def __init__(self,base,height):
        self.base=int(base)
        self.height = int(height)
        
    def area(self):
        return self.height * self.base
    def perimeter(self):
        return 2 * (self.height + self.base)
        
base = input("What is the base of your rectangle?:")
height = input ("What is the height of your rectangle?:")
rectangle = Rectangle(base,height)
print("The area of the rectangle is {} and its perimeter {}".format(rectangle.area(),rectangle.perimeter()))

You note that we no longer need to start our work by first cleaning up the data, that part was already done!

##Assignment

Write code that will satisfy the following requirements

    As a user, I want to pass the radius of a circle and have it give to me the area and the perimeter of the circle

##References

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment