The Disk Class
Understanding Object-Oriented Programming in Python
Object-Oriented Programming (OOP) is a programming paradigm that organizes code into reusable "blueprints" called classes. Each class defines the structure and behavior of objects that can be created from it.
Think of a class as a cookie cutter, and objects as the cookies! The Disk class is our blueprint for creating circular shapes in our spooky ghost project.
Each disk object can have different properties (like color and size) but shares the same basic structure and abilities.
π― Disk Class Overview
The Disk class represents a circular shape with customizable properties. It's the foundation for building more complex objects like eyeballs and ghost heads!
Attributes (Instance Variables):
| Attribute | Type | Description |
|---|---|---|
center |
tuple (x, y) | Position of the disk's center on the canvas |
radius |
float | Size of the disk (distance from center to edge) |
thickness |
float | Width of the outline/stroke (0 = no outline) |
bg_color |
color | Fill color inside the disk |
stroke_color |
color | Color of the outline/border |
Methods (Actions):
__init__()- Constructor that creates a new Disk object__repr__()- Returns a string description of the Diskrender()- Draws the disk on the screenset_center()- Changes the disk's positionset_bg_color()- Changes the fill colorset_stroke_color()- Changes the outline color
π Complete Disk Class Code
The class keyword tells Python we're creating a new class. The name Disk follows Python naming conventions (PascalCase for classes).
The colon : starts the class body, and everything indented below belongs to the class.
1class Disk: 2 """ 3 Attributes: 4 center: a tuple of decimals - (x, y) 5 radius: a decimal >= 0 6 thickness: stroke thickness - a decimal >= 0 7 colors: a tuple: (bg, stroke) with HSB colors 8 """
The __init__ method is called automatically when you create a new Disk object. It's like the "birth" of an object! This special method initializes all the attributes (instance variables) that each disk will have.
Key Concepts:
self- Refers to the specific object being created. It's how the object "knows itself"!self.attribute_name- Creates an instance variable that belongs to this specific object- Parameters like
center,radius, etc. are the values passed in when creating a Disk
10 def __init__(self, center, radius, thickness, colors): 11 self.center = center 12 self.radius = radius 13 self.thickness = thickness 14 self.bg_color = colors[0] 15 self.stroke_color = colors[1] 16 #end init
The __repr__ method is another special "magic method" in Python. It defines how your object appears when you print it or view it in the console. Think of it as giving your object a "voice" to describe itself!
Why is this useful? When debugging, you can simply print a Disk object and see its properties without accessing each attribute individually.
Java Connection: This is similar to the toString() method in Java!
18 #acts as a 'representative' of the object in the same way as 'toString' acts in Java 19 def __repr__(self): 20 # Using standard string concatenation for compatibility with older Python versions in Processing 21 msg = "Disk at: (" + str(self.center[0]) + ", " + str(self.center[1]) + "); " 22 msg += "radius = " + str(self.radius) + "; thickness = " + str(self.thickness) 23 # Note: hue() is a Processing function 24 if self.bg_color: 25 msg += "; Approx hue = " + str(round(hue(self.bg_color), 2)) 26 return msg 27 #end repr
This is where the magic happens! The render() method draws the disk on the screen using Processing's drawing functions. This method demonstrates encapsulation - all the logic for drawing a disk is contained within the Disk class itself.
Key Features:
- Local variables (x, y, r, t, bg, sc) make the code easier to read
- Conditional logic handles different cases (with/without stroke, with/without fill)
- Processing functions like
stroke(),fill(), andellipse()do the actual drawing - The method uses
selfto access the object's own attributes
29 def render(self): 30 # create some working copies for easier coding 31 x = self.center[0] 32 y = self.center[1] 33 r = self.radius 34 t = self.thickness 35 bg = self.bg_color 36 sc = self.stroke_color 37 38 # Set stroke settings based on thickness 39 if t > 0: 40 if sc == None: 41 sc = color(0, 0, 0) # default to black if no stroke color 42 stroke(sc) 43 strokeWeight(t) 44 else: 45 noStroke() 46 strokeWeight(0) 47 48 # Set fill settings 49 if bg != None: 50 fill(bg) 51 else: 52 noFill() 53 54 # Draw the disk (Processing uses width/height, so 2*r) 55 ellipse(x, y, 2*r, 2*r) 56 #end render
Setter methods allow us to safely change an object's properties after it's been created. This is an important OOP principle called encapsulation - we control HOW the object's data is modified.
Why not just change the attribute directly? Setter methods allow us to add validation, trigger side effects, or maintain consistency. For example, we could add a check to ensure the radius is never negative!
58 def set_center(self, location): 59 #location is a (x,y) tuple 60 self.center = location 61 #end set_center 62 63 def set_bg_color(self, bg): 64 self.bg_color = bg 65 #end set_bg_color 66 67 def set_stroke_color(self, strk): 68 self.stroke_color = strk 69 #end set_stroke_color 70 71#end class Disk
Here's how you create and use a Disk object in your code:
# Step 1: Create a color (in HSB mode) my_orange = color(30, 100, 100) # Hue, Saturation, Brightness my_black = color(0, 0, 0) # Step 2: Create a Disk object # Parameters: center, radius, thickness, (bg_color, stroke_color) ghost_head = Disk((250, 200), 50, 2, (my_orange, my_black)) # Step 3: Use the Disk's methods ghost_head.render() # Draw it on screen # Step 4: Modify the Disk ghost_head.set_center((300, 250)) # Move it ghost_head.render() # Draw it in new position # Step 5: Check what it looks like print(ghost_head) # Calls __repr__ automatically!
π§ Key OOP Concepts in the Disk Class
1. Class
A blueprint/template for creating objects. Our Disk class defines what every disk should have and be able to do.
2. Object/Instance
A specific disk created from the class. Each ghost head, eyeball base, and pupil is a different Disk object.
3. Attributes
Data that belongs to an object (center, radius, color, etc.). Each disk has its own unique values for these attributes.
4. Methods
Actions/behaviors that objects can perform (render, set_center, etc.). These are functions that belong to the class.
5. Encapsulation
Bundling data (attributes) and methods together. The Disk knows how to draw itself - other code doesn't need to know the details!
6. self Parameter
Refers to the specific object instance. It's how methods access the object's own attributes and other methods.
Try these coding challenges to deepen your understanding:
- Add a
get_area()method that calculates and returns the area of the disk (Ο Γ radiusΒ²) - Add a
set_radius()method that includes validation (radius must be > 0) - Create a
move()method that takes dx and dy parameters to shift the disk by that amount - Add a
contains_point()method that checks if a given (x, y) point is inside the disk - Create a method that makes the disk "pulse" by gradually changing its radius over time
Explore More Classes
Continue learning about OOP with our other classes: