I am very new to Python and Object Oriented Programming. I'm performing this tutorial that uses the p5 library.
The tutorial's posted code is like:
from p5 import setup, draw, size, background, run
import numpy as np
from boid import Boid
width = 1000
height = 1000
def setup():
#this happens just once
size(width, height) #instead of create_canvas
def draw():
#this happens every time
background(30, 30, 47)
run()
But when I try to run it, all sorts of errors occur unless I place "p5." before the functions background()
, size()
, and run()
:
... p5.size()
... p5.background()
... so on
I have had this confusion at other similar codes; sometimes the library name was used before the function, sometimes it wasn't, so the code above is just an example to show my general ignorance on the topic.
Any explanations or directions to where I could learn about this are welcome.
Cheers.
When you do:
from p5 import setup, draw, size, background, run
The names setup
, draw
etc. are added to the global namespace and bound to the proper library functions/objects (i.e. those from the p5
library)
But after that, when these lines run:
def setup():
...
def draw():
The names setup
& draw
are changed to point to the functions you just define, so they are not bound to the p5
library objects anymore.
Due to the ambiguity in the names, the script might run into errors. However, your script should be okay since those re-defined names don't seem to be used anywhere.
Using the p5.
prefix just clears up that confusion & fixes the issue.
It's always best practice the use the library.
prefix if the library exports names that are generic like setup
, draw
etc. Or if the name clashes with your own names / other librarys exported names.