Newbie trying to understand __name__=='__main__'

Luc Lefebvre lefebvre at med.mcgill.ca
Mon Sep 18 14:33:29 EDT 2000


Hi,

I have been reading "Learning Pyton" and tried this code:

"""
    From Learning Python
    page 175
    Implements Set class and methods
"""

class Set:
    def __init__(self, value=[]):
        self.data=[]
        self.concat(value)

##     def intersect(self,other):
##         res=[]
##         for x in self.data:
##             if x in other:
##                 res.append(x)
##         return Set(res)

##     def union(self,other):
##         res=self.data[:]
##         for x in other:
##             if not x in res:
##                 res.append(x)
##         return Set(res)

    def concat(self,value):
        for x in value:
            if not x in self.data:
                self.data.append(x)

    def __len__(self):          return len(self.data)
    def __getitem__(self,key):  return self.data[key]
##     def __and__(self,other):    return self.intersect(other)
##     def __or__(self,other):     return self.union(other)
    def __repr__(self):         return "Set:" + `self.data`

    if __name__=='__main__':
        print "running as \'main\'"
        print "doesn't seem to want to run code below..."
        x=Set([1,2,3,4])
        #y=Set([3,4,5])
        #x&y
        #x|y
        #z=Set('hello')
        #z[0], z[-1]
        #for c in z: print c,
        #len(z), z
        #z& "mello", z | "mello"

### running this yields:


running as 'main'
doesn't seem to want to run code below...
Traceback (innermost last):
  File "<stdin>", line 7, in ?
  File "<stdin>", line 40, in Set
NameError: Set

###
line 40 is 'x=Set([1,2,3,4])
line 7 is 'class Set:'

I would have expected this to work....



More information about the Python-list mailing list