Skip to main content
 首页 » 编程设计

Python:如何在此类中实现 'pop'

2025年05月04日11mengfanrong

我希望这个类像一个列表。它的数据驻留在属性 self.data 中。 如果我有一个实例,pp = population,定义 __getitem__ 意味着我可以引用 pp 而不是 pp.data?或者它是 __repr__ 的定义吗? 从列表而不是对象派生此类会为我提供“流行”。 现在我需要实现'pop'方法。谢谢

class population (object): 
def __init__ (self): 
    self.data = [] 
 
def append(self, item): 
    self.data.append(item) 
 
def extend(self, item): 
    self.data.extend(item) 
 
def sort(self): 
    self.data.sort(cmp=fitnesscompare) 
 
def __getitem__(self, index): return self.data[index] 
 
def __setitem__(self, index, item): self.data[index] = item 
 
def __len__(self): return len(self.data) 
 
def __repr__(self): return repr(self.data) 
 
def copy(self): 
    return copy.deepcopy(self) 

请您参考如下方法:

为什么不直接扩展列表类呢?然后您就拥有了所有这些内置功能。<​​/p>

class population(list): 
    # custom methods here 

请记住,不要为列表引用 self.data,而只需引用 self。