0

I'm making a random circle-drawing program. After the circles are drawn, it converts the turtle graphic to a PNG. I'm getting an error that reads "NameError: name 'self' is not defined". Does anyone know why?

import random  
import time  
import turtle
import os

print("Abstract Art Template Generator")
print()
print("This program will generate randomly placed and sized circles on a blank screen.")
num = int(input("Please specify how many circles you would like to be drawn: "))
radiusMin = int(input("Please specify the minimum radius you would like to have: "))
radiusMax = int(input("Please specify the maximum radius you would like to have: "))
screenholder = input("Press ENTER when you are ready to see your circles drawn: ")

t = turtle.Pen()
wn = turtle.Screen()

def mycircle():
    x = random.randint(radiusMin, radiusMax) 
    t.circle(x)

    t.up()
    y = random.randint(0, 360)
    t.seth(y)
    if t.xcor() < -300 or t.xcor() > 300:
        t.goto(0, 0)
    elif t.ycor() < -300 or t.ycor() > 300:
        t.goto(0, 0)
    z = random.randint(0, 100)
    t.forward(z)
    t.down()


for i in range(0, num):
    mycircle()


cv = turtle.getcanvas()
cv.postscript(file="template.ps", colormode='color')

os.system("mkdir / template.ps")
os.system("gs -q -dSAFER  -sDEVICE=png16m -r500 -dBATCH -dNOPAUSE  -dFirstPage=%d -dLastPage=%d -sOutputFile=/template.png %s" %(i,i,self.id,i,psname))


turtle.done()
unor
  • 92,415
  • 26
  • 211
  • 360
TimRin
  • 77
  • 7
  • "os.system("gs -q -dSAFER -sDEVICE=png16m -r500 -dBATCH -dNOPAUSE -dFirstPage=%d -dLastPage=%d -sOutputFile=/template.png %s" %(i,i,self.id,i,psname))" There are only 3 "%" somethings and you are passing in 5 values & one of them is the mysterious "self.id". Looks like a copy and paste bug. – Jason De Arte Mar 05 '16 at 01:42

2 Answers2

1

Look at your last os.system line, you're trying to interpolate self.id which is undefined.

Simon Charette
  • 5,009
  • 1
  • 25
  • 33
1

In Python, self is usually used within classes (objects) to reference the object you are working with. It is possible to use self without a class as a variable, but it needs to be defined first.

In your code, you did not define self to be equal to anything, so the code does not know what to do with it.

If you are trying to use it to access an object, it can not be done this way. It must be done inside of a class, similar to the way this works in Java.

This answer might help you understand self in Python.

Community
  • 1
  • 1
Buzz
  • 1,877
  • 21
  • 25
  • 1
    `self` always needs to be defined (whether in an instance method or not), but when you call an method on an object, that instance is automatically passed as the first argument (traditionally called `self`). – Paul Mar 05 '16 at 01:56