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:
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:
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:
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.
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.
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.
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:
- 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.
- 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?
- Verify one method numerically: hand-calculate volume() (or your equivalent) for given dimensions and show the object agrees.
- From the quiz prompt: one question you missed and the corrected answer.
