简体   繁体   中英

How to create an instance of a class inside a method within the class, python

My class deals with lists of ints and computing them so they don't have reoccurring values. I have implemented a new method 'intersect' which takes in two intSet objects and creates a new object with the values that appear in both objects lists (vals).

Origially i was creating a new list inside the method (instead of an object) to add the ints found in both lists however i thought it would be fitting to create a new object and add the values to val in the new object. However I get the error NameError: global name 'inSet' is not defined

Here's my code:

class intSet(object):
    """An intSet is a set of integers
    The value is represented by a list of ints, self.vals.
    Each int in the set occurs in self.vals exactly once."""

    def __init__(self):
        """Create an empty set of integers"""
        self.vals = []

    def insert(self, e):
        """Assumes e is an integer and inserts e into self""" 
        if not e in self.vals:
            self.vals.append(e)

    def member(self, e):
        """Assumes e is an integer
           Returns True if e is in self, and False otherwise"""
        return e in self.vals

    def remove(self, e):
        """Assumes e is an integer and removes e from self
           Raises ValueError if e is not in self"""
        try:
            self.vals.remove(e)
        except:
            raise ValueError(str(e) + ' not found')

    def __str__(self):
        """Returns a string representation of self"""
        self.vals.sort()
        return '{' + ','.join([str(e) for e in self.vals]) + '}'

    def intersect(self, other):
        #intersected = []
        intersected = inSet()
        for x in self.vals:
            if x in other.vals:
                #intersected.append(x)
                intersected.insert(x)
        return intersected


a= {-15,-14,-5,-2,-1,1,3,4,11,18}
b= {-12,-3,3,8,12,16,18,20}
set1 = intSet()
set2 = intSet()
[set1.insert(x) for x in a]
[set2.insert(x) for x in a]

print set1.intersect(set2)

Bonus question, most the code was written by the admins for the MOOC, 6.00.1x. I just had to implement the 'intersect' method. Why are curly braces which are for dictionary purposes used instead on list [] braces ?

It's intSet, not inSet, you've misspelled it in your intersect method. And as a habit it's better to start your classes with a capital (although there are no fixed rules, this is a habit widely adhered to).

About the curly braces, they are not only for dictionaries but also for Python sets. So by using them in the __str__ method, the output suggests that instances of your class are indeed a kind of sets.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM