Pergunta

I have created a new class under UserList called UList that overrides the __add__ method - it does not allow duplicate items to be added to a list. But when I try to run it, I don't get the expected results:

from collections import UserList

class UList(UserList):
  def append(self,ap_item):
    for ap in ap_item:
        if ap in self:
          raise ValueError(repr(ap) + " already exists in list")
        else:
          return UserList.append(self, ap_item)
  def __add__(self,ad_item):
    for ad in ad_item:
        if ad in self:
          raise ValueError(repr(ad) + " already exists in list")
        else:
          return UserList.__add__(self,ad_item)
  def extend(self, ex_item):
    for ex in ex_item:
        if ex in self:
          raise ValueError(repr(i) + " already exists in list")
        else:
          return UserList.extend(self,ex_item)

How can I get this method to execute correctly?

Foi útil?

Solução

Your __add__ function lacks a return statement. Any function so lacking implicitly returns None. That explains why your function returns None.

Try this:

return UserList.__add__(self,ad_item)
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top