Back to Resources

Classes

by Eddie Huang, Brad Solomon

A class is to a car factory as an object is to a car. Classes define the behavior of a type of object. They contain variables and functions that are inherent to the class.

A Simple Rectangle Example

rectangle.py

class Rectangle:
    def __init__(self,w=5,h=5):
        self.w = w
        self.h = h

    def area(self):
        return self.w * self.h
    
    def circumference(self):
        return (self.w + self.h) * 2

main.py

from rectangle import *

if __name__ == '__main__':
    r1 = Rectangle(3,4)
    r2 = Rectangle()
    print(r1.area())
    print(r2.circumference())

Output

r1 area: 12
r2 circumference: 20