Python Classes

A Python class is a blueprint for creating objects with similar properties and behaviors. It allows you to define attributes (variables) and methods (functions) that can be associated with the objects created from the class. Classes provide a way to organize and structure code, promoting code reusability and modularity. Here's a simple example of a Python class:

class Rectangle:
    def __init__(self, length, width):
        self.length = length
        self.width = width

    def area(self):
        return self.length * self.width

    def perimeter(self):
        return 2 * (self.length + self.width)

The class called Rectangle has two attributes: length and width, which are initialized using the __init__ method (a special method in Python classes that is automatically called when an object is created).

The class also has two methods: area() and perimeter(). The area() method calculates and returns the area of the rectangle by multiplying the length and width attributes. The perimeter() method calculates and returns the perimeter of the rectangle by adding the lengths of all sides. Here's how to create objects from the Rectangle class and use the methods:

# Create a rectangle object with length 5 and width 3
my_rectangle = Rectangle(5, 3)

# Calculate and print the area
print("Area:", my_rectangle.area())

# Calculate and print the perimeter
print("Perimeter:", my_rectangle.perimeter())

Output:

Area: 15
Perimeter: 16

An instance of the Rectangle class called my_rectangle is created with a length of 5 and width of 3. Calling the area() and perimeter() methods on my_rectangle calculates and displays the area and perimeter of the rectangle, respectively.

Python Package as Classes

Packages are implemented as classes that combine properties (values), methods (functions), and data. An example is the package Numpy.

import numpy as np
print('pi = {0:.10f}'.format(np.pi)) # property: np.pi
print(np.linspace(0,10,11))          # method: np.linspace
 pi = 3.1415926536
 [ 0.  1.  2.  3.  4.  5.  6.  7.  8.  9. 10.]

The following tutorial is an introduction on how to create a Python class with initialization, methods, and properties.

Create a Dog Class

This is an example with a Dog class with instances Tony and Princess.

class Dog:
    def __init__(self,name):
        self.name = name
        self.tricks = []
        return

    def add_trick(self,trick):
        self.tricks.append(trick)
        return

    def show_tricks(self):
        print(self.name+"'s tricks are:")
        for x in self.tricks:
            print(x)

d = Dog('Tony')
d.add_trick('sprint')
d.add_trick('sleep')
d.name = 'Tony2'
d.show_tricks()

e = Dog('Princess')
e.add_trick('sit')
e.add_trick('roll over')
e.eye_color = 'Brown'
e.show_tricks()

Generative AI Learning

Use these prompts to test your understanding after completing the tutorial. Classes are a design exercise, so the specify step matters more than the code: decide the attributes and methods before anyone - you or the AI - writes a line.

"Quiz me with 5 questions, one at a time, on Python classes: what a class is versus an instance (blueprint versus object), what __init__ does and what self refers to, the difference between an attribute and a method using the Rectangle example (length, width vs area(), perimeter()), why the Dog objects Tony and Princess keep separate trick lists, and how numpy itself is an example of classes (properties like pi, methods like linspace). Grade my answers and list my misconceptions."
"I will specify a class; generate Python ONLY from my spec, then help me break it. My spec: a Tank class with attributes {diameter, height, level}, methods {volume(), fill(rate, time) that raises the level, and is_overflowing()}, units {state them}, and rules {level can never be negative or above height}. After the code, give me 4 test cases including two that try to violate the rules. I will run them and report which rules the generated class actually enforces - then we fix the gaps together, with me stating the fix before you code it."

Tip: The gap between "the spec said level can never exceed height" and "the code actually prevents it" is where real software fails. Testing the rules, not just the happy path, is the audit skill - the same one you will use on every AI-generated class, including the tclab.TCLab class in the course project.

What to Turn In

Submit a short report (PDF, 1-2 pages) that curates your results into a demonstration of what you learned. You may use Generative AI to help write the report, but you must guide it to the correct code, justifications, and assumptions. Answer these questions:

  1. Include a class you wrote yourself (Rectangle-level or your own engineering object) with __init__, two attributes, and two methods, plus a script that creates two instances and shows they keep independent state.
  2. Include your Tank (or equivalent) spec, the generated class, and the results of the 4 tests. Which rule was not enforced on the first try, and what was the fix?
  3. Verify one method numerically: hand-calculate volume() (or your equivalent) for given dimensions and show the object agrees.
  4. From the quiz prompt: one question you missed and the corrected answer.

Course Information

Excel and VBA

Python

MATLAB

MathCAD

Related Courses

Admin