Search code examples
python-3.xoopinstances

Python OOP, cannot overwrite instances


I want to make 2 instances with same name like,

a = SomeClass(someAttr1) 
a = SomeClass(someAttr2) 

so that the new one should overwrite the previous one.

I also tried this:

a = SomeClass(someAttr1) 
a = None
a = SomeClass(someAttr2) 

I tried this but it doesn't overwrite the previous instance and adds it in itself, is there any way to do it?

Here is the code:

### Do not change the Location or Campus classes. ###
### Location class is the same as in lecture.     ###
class Location(object):
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def move(self, deltaX, deltaY):
        return Location(self.x + deltaX, self.y + deltaY)

    def getX(self):
        return self.x

    def getY(self):
        return self.y

    def dist_from(self, other):
        xDist = self.x - other.x
        yDist = self.y - other.y
        return (xDist ** 2 + yDist ** 2) ** 0.5

    def __eq__(self, other):
        return (self.x == other.x and self.y == other.y)

    def __str__(self):
        return '<' + str(self.x) + ',' + str(self.y) + '>'


class Campus(object):
    def __init__(self, center_loc):
        self.center_loc = center_loc

    def __str__(self):
        return str(self.center_loc)


class MITCampus(Campus):
    """ A MITCampus is a Campus that contains tents """
    tents_list = []
    def __init__(self, center_loc, tent_loc=Location(0, 0)):
        """ Assumes center_loc and tent_loc are Location objects
        Initializes a new Campus centered at location center_loc
        with a tent at location tent_loc """
        # Your code here
        Campus.__init__(self, center_loc)
        self.tent_loc = tent_loc
        self.tents_list.append(self.tent_loc)

    def add_tent(self, new_tent_loc):
        """ Assumes new_tent_loc is a Location
        Adds new_tent_loc to the campus only if the tent is at least 0.5 distance
        away from all other tents already there. Campus is unchanged otherwise.
        Returns True if it could add the tent, False otherwise. """
        # Your code here

        new_tent_flag = True
        for loc in self.tents_list:
            if loc == new_tent_loc or new_tent_loc.dist_from(loc) < 0.5:
                new_tent_flag = False

        if new_tent_flag:
            self.tents_list.append(new_tent_loc)
            return True
        else:
            return False


    def get_tents(self):
        """ Returns a list of all tents on the campus. The list should contain
        the string representation of the Location of a tent. The list should
        be sorted by the x coordinate of the location. """
        # Your code here
        new_list_sorted = sorted(self.tents_list, key=lambda tent: tent.getX())
        str_list = []
        for x in new_list_sorted:
            str_list.append(x.__str__())

        return str_list

Test Cases:

Test: 0


        c = MITCampus(Location(1,2))
        print(c.add_tent(Location(1,2)))
        print(c.add_tent(Location(0,0)))
        print(c.add_tent(Location(2,3)))
        print(c.add_tent(Location(2,3)))
        print(c.get_tents())


Output:

    True
    False
    True
    False
    ['<0,0>', '<1,2>', '<2,3>']

Test: 1


        init campus with default tent loc
        c = MITCampus(Location(-1,-2))
        print(sorted(c.get_tents()))


Output:

    ['<0,0>','<0,0>', '<1,2>', '<2,3>']

Expected Output:

        ['<0,0>']

As can be seen that the second instance should overwrite the previous one but instead it is adding it. Is the problem in the code? and how to solve it?


Solution

  • Ok, Your tents_list attribute is a class atribute, so even when your c object is overwrited the tents_list attribute stays the same. It's better to make your tents_list an object argument so the tents_list attribute is overwrited too.

    def __init__(self, center_loc, tent_loc=Location(0, 0)):
        Campus.__init__(self, center_loc)
        self.tents_list = []  # <--- Add this
        self.tent_loc = tent_loc
        self.tents_list.append(self.tent_loc)