SimpleNamespace
Overview
We can use a SimpleNamespace instance to store properties in an object.
Soon we will learn how to write our own classes, which is a more powerful
way to do this. SimpleNamespace lets us use some of the power of OOP
more easily.
This is a fine first step before we learn more about OOP (soon!).
Note: unfortunately, SimpleNamespace does not run properly
as of now in the version of Brython used by these notes, but it does run
properly in the CS Academy sandbox and (of course) in Python on
your laptop.
Basic Example
Study the example below. Specifically:
- makeDot() creates a dot object (an instance of SimpleNamespace),
with the properties cx, cy, r, and color.
- testMakeDot() shows you how you can create and use these dot instances.
from types import SimpleNamespace
def makeDot(cx, cy, r, color):
# 1. Create a new instance of SimpleNamespace (with no properties set yet):
dot = SimpleNamespace()
# 2. Initialize the new instance with the properties:
dot.cx = cx
dot.cy = cy
dot.r = r
dot.color = color
# 3. return the new instance:
return dot
def testMakeDot():
print('Testing makeDot()...', end='')
# 1. Make a new dot object:
dot = makeDot(200, 200, 50, 'blue')
# 2. It has the given properties:
assert(dot.cx == 200)
assert(dot.cy == 200)
assert(dot.r == 50)
assert(dot.color == 'blue')
# 3. We can change properties:
dot.cx += 50
assert(dot.cx == 250)
# 4. We can add new properties:
dot.counter = 42
assert(dot.counter == 42)
# 6. We can use == and !=:
dot1 = makeDot(200, 200, 50, 'blue')
dot2 = makeDot(200, 200, 50, 'blue')
dot3 = makeDot(200, 200, 50, 'red')
assert((dot1 == dot2) and (dot1 != dot3))
# 7. We can convert the dot to a string:
assert(str(dot1) == "namespace(cx=200, cy=200, r=50, color='blue')")
# 8. The type of the dot is SimpleNamespace:
assert(type(dot1) == SimpleNamespace)
print('Passed!')
testMakeDot()
Animation Example
makeDot() is a very convenient way for us to store all the properties of dots
in the following animation example:
from cmu_graphics import *
from types import SimpleNamespace
import random
def onAppStart(app):
app.dots = [ ]
def onMousePress(app, mouseX, mouseY):
r = random.randrange(5, 50)
color = random.choice(['red', 'orange', 'yellow', 'green', 'blue', 'purple'])
dot = makeDot(mouseX, mouseY, r, color)
app.dots.append(dot)
print('Added:', dot)
def makeDot(cx, cy, r, color):
dot = SimpleNamespace()
dot.cx = cx
dot.cy = cy
dot.r = r
dot.color = color
return dot
def redrawAll(app):
drawDots(app)
drawTitleAndInstructions(app)
def drawTitleAndInstructions(app):
drawLabel('SimpleNamespace Demo', app.width/2, 20, size=16, bold=True)
drawLabel('Click mouse to create random dots', app.width/2, 40, size=14)
def drawDots(app):
for dot in app.dots:
drawCircle(dot.cx, dot.cy, dot.r, fill=dot.color)
def main():
runApp()
main()