【问题标题】:Problem When Creating Custom Class in Python在 Python 中创建自定义类时的问题
【发布时间】:2022-01-13 08:31:56
【问题描述】:

使用下面的代码:


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))

我得到输出:

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

请注意,def union(self, other) 没有添加从 set2 到 set1 的所有唯一数字。但是,如果我使用:

print(set1.union(set2.vals))

然后我得到:

[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]

这是什么原因造成的?我假设.union(set2) 中的 set2 处于初始化时的状态(因此它是一个空列表)。但是我在里面插入了一些数字并打印出来

【问题讨论】:

  • 你为什么不直接使用set 而不是上课??!
  • 您没有接受任何回答。没有一个答案能解决您的问题吗?您需要更多信息吗?

标签: python class oop methods


【解决方案1】:

您的问题是您试图从类本身读取值,您使用的是other 而不是other.vals。当您尝试使用时,您已经回答了您的问题

print(set1.union(set2.vals)) 

所以你可以把你的函数改成这样:

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

【讨论】:

    【解决方案2】:

    您在Int_set 的实例上调用len。这派生自list,并为您提供实例本身的长度,即0。你需要在你的类中覆盖__len__ 并返回实例val 的值。

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

    你也必须改变你的union 方法。目前您遍历Int_set 实例的成员并且没有。您必须遍历 vals 属性。

    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
    

    总体而言,不清楚您为什么决定将Int_set 设为list 的子类,因为您不使用list 类中的任何功能。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-18
      • 2012-09-23
      相关资源
      最近更新 更多