Python noob needs help with syntax

For questions about using Classic.

Post » Tue Dec 21, 2010 11:38 pm

[code:1r9ehp96]import random

class RmDef(object):
def __init__(self, x, y, width, height, roomvar):
width = 0
roomvar = random.randint(1,3)

if roomvar == 1:
width = random.randint(2, 4)
elif roomvar == 2:
width = random.randint(4, 6)
elif roomvar == 3:
width = random.randint(6, 8)[/code:1r9ehp96]

Receiving this error

[code:1r9ehp96]nameError: "width" is not defined[/code:1r9ehp96]

I'm confused cause I'm defining width to be = 0. So why is it saying it's not defined?
B
5
S
2
G
3
Posts: 36
Reputation: 1,622

Post » Wed Dec 22, 2010 2:05 am

You are not defining in the right scope. I guess you want x, y, width, height and roomvar being members of the class and to be able to pass values to them when initializing the class?

When using a variable name you are creating it on a global scope. To make it local you need to use 'self' within the class. Also 'width' and 'self.width' are then two different variables (they have different scope) and 'width' within the parantheses of __init__ is a parameter to that function.

If you want a class that can be initialized with parameters {by calling something like "rd = RmDef(y=20, width=32)"} do this:
[code:1jsbbyde]import random

class RmDef(object):
def __init__(self, x=0, y=0, width=0, height=0, roomvar=0):
self.x = x
self.y = y
self.width = width
self.height = height
self.roomvar = roomvar

self.roomvar = random.randint(1,3)

if self.roomvar == 1:
self.width = random.randint(2, 4)
elif self.roomvar == 2:
self.width = random.randint(4, 6)
elif self.roomvar == 3:
self.width = random.randint(6, 8)[/code:1jsbbyde]
If your class doesn't need initialization parameters, do this:
[code:1jsbbyde]import random

class RmDef(object):
def __init__(self):
self.x = 0
self.y = 0
self.width = 0
self.height = 0
self.roomvar = 0

self.roomvar = random.randint(1,3)

if self.roomvar == 1:
self.width = random.randint(2, 4)
elif self.roomvar == 2:
self.width = random.randint(4, 6)
elif self.roomvar == 3:
self.width = random.randint(6, 8)[/code:1jsbbyde]

It is good practice to always set the variables at the start of __init__ even if they won't be used at that moment. This way you don't lose overview.
Image
B
23
S
8
G
10
Posts: 1,820
Reputation: 8,242

Post » Wed Dec 22, 2010 5:15 am

Thank you, I appreciate your help good sir.
B
5
S
2
G
3
Posts: 36
Reputation: 1,622


Return to Help & Support using Construct Classic

Who is online

Users browsing this forum: No registered users and 9 guests