Home > other >  Problem When Creating Custom Class in Python
Problem When Creating Custom Class in Python

Time:12-08

With the code below:


class Int_set(list):
def __init__(self):
    self.vals=[]
    self.index=0
    
def insert(self, elm): #assume a string of numbers
    for x in elm:
        if x not in self.vals:
            self.vals.append(int(x))
    return self.vals
            
def member(self, elm):
    return elm in self.vals 

def remove(self, elm):
    try:
        self.vals.remove(elm)
    except:
        raise ValueError(str(elm) ' not found')
        
def get_members(self):
    return self.vals[:]

def __str__(self):
    if self.vals == []:
        return '[]'
    self.vals.sort()
    result = ''
    for e in self.vals:
        result = result   str(e)   ','
    return f'{{{result[:-1]}}}'
   
def union(self, other):
    '''add all non-duplicate elements from other set to self set'''
    print(len(other))
    for e in range(len(other)):
        if other[e] not in self.vals:
            self.vals.append(other[e])
        else:
            continue
    return self.vals

set1=Int_set()
set1.insert('123456')
print(set1.get_members())

set2=Int_set()
set2.insert('987')
print(set2.get_members())

print(set1.union(set2))

I get output:

[1, 2, 3, 4, 5, 6]
[9, 8, 7]
0 # the print(len(other)) in def union
[1, 2, 3, 4, 5, 6]

Notice that the def union(self, other) did not add in all the unique numbers from set2 to set1. However, if I use:

print(set1.union(set2.vals))

then I get:

[1, 2, 3, 4, 5, 6]
[9, 8, 7]
3 # the print(len(other)) in def union
[1, 2, 3, 4, 5, 6, 9, 8, 7]

What is causing this? I assume set2 inside .union(set2) was in the state when it was initialized(thus it's an empty list). But I inserted some numbers inside and printed it out

CodePudding user response:

You call len on the instance of Int_set. This is derived from list and gives you the length of the instance itself which is 0. You need to overwrite __len__ in your class and give back the value of the instances val.

def __len__(self):
    return len(self.vals)

And you have to change your union method too. At the moment you iterate over the members of the instance of Int_set and there are none. You have to iterate over the vals attribute.

def union(self, other):
    '''add all non-duplicate elements from other set to self set'''
    print(len(other))
    for element in other.vals:
        if element not in self.vals:
            self.vals.append(element)
        else:
            continue
    return self.vals

Overall it's unclear why you decided to make Int_set a subclass of list since you use no features from the list class.

CodePudding user response:

Your problem is that you are trying to read values from class itself, you are using other instead of other.vals. You have answered your question when you tried with

print(set1.union(set2.vals)) 

So you can change your function to this:

def union(self, other):
        '''add all non-duplicate elements from other set to self set'''
        print(len(other.vals))
        for e in range(len(other.vals)):
            if other.vals[e] not in self.vals:
                self.vals.append(other.vals[e])
            else:
                continue
        return self.vals
  • Related