I'm learning Python, mainly through the MIT OpenCourseWare project. I'm trying to do problem 2 of assignment 9 here.
It has a shell of code that simply has the class and def headers with comments. I added the actual code below
class ShapeSet:
def __init__(self):
"""
Initialize any needed variables
"""
self.set1=[]
set1=self.set1
def addShape(self, sh):
"""
Add shape sh to the set; no two shapes in the set may be
identical
sh: shape to be added
"""
self.set1=[]
set1=self.set1
a=True
for x in set1:
if x==sh:
a=False
if a:
set1.append(sh)
return set1
print(set1[:])
There is code above this that creates classes for the different shapes. It's giving me no problems so I didn't include it. This is my first time doing OOP so I have a few questions.
In IDLE, I say
s=ShapeSet()
to create an instance. I have to do this each time because otherwise it disappears and I get aNameError
that's' is not defined
. Why doesn't it persist?Probably related to that, I can successfully use
addShape
to add a shape once, but the set never contains more than one shape, no matter how many I try to add.You see that I have set1 defined in there twice. If I just put it in
__init__
, like I assumed I should do, I get an error thatset1
is not defined. Why would it be undefined if it's in init? Related, I was always confused about how things are named in classes. Why do people always renamex=self.x
? Is it OK to just call itset1
to begin with and avoid theself.set1
?