0
class lista(object):
    listanumere=[]
    def printer(self):
        print self.listanumere
    def adds(self,numar):
        self.listanumere.append(numar)

class movies():
    def __init__(self,ide,nume):
        self.__nume=nume
        self.__ide=ide

listarez=lista
a=movies(1,"David")
lista.adds(a)
lista.printer()

Error:

TypeError: unbound method adds() must be called with lista instance as first argument (got movies instance instead)  

So my question is: How to make a class which contains a list of elements defined in another class, for example a class which contains the list of movies and some methods which modify the list for example add a new movie or remove a movie with a certain ID?

3
  • Code is unreadable, fix please. Commented Nov 7, 2012 at 12:45
  • You'll need to fix the code in your __init__ method, it's unclear what the intent is there, you have several statements on the same line without indentation. Commented Nov 7, 2012 at 12:46
  • 1
    what do you want you lista class to do that a plain old list doesn't already do? Commented Nov 7, 2012 at 12:50

2 Answers 2

6

You seem to be mixing up class methods and instance methods. You probably wanted to do:

listarez = lista()

And then

listarez.adds(a)
listarez.printer()
Sign up to request clarification or add additional context in comments.

1 Comment

I would also point out that listanumere is a class attribute, which means that every lista instance shares the same list, and that this might not be what OP intended. To fix, remove listanumere = [], give lista an __init__ method with self.listanumere = [] in it instead.
1

Short answer :

class lista(object):
    listanumere=[]
    def printer(self):
        print "\n".join( [ str(elem)for elem in self.listanumere ] )
    def adds(self,numar):
        self.listanumere.append(numar)

class movies():
    def __init__(self,ide,nume):
        self.__nume=nume
        self.__ide=ide
    def __str__(self):
        return ":".join( [ str(self.__nume) , str(self.__ide) ] )


listarez=lista()
a=movies(1,"David")
b=movies(2,"Goliath")

listarez.adds(a)
listarez.adds(b)

listarez.printer()

If I were you, I would go with a class derived from a dictionnary (e.g. {'ID string' : movie object }) with the right overload method (init, str,..). That way you take avantage of standard methods such as itertools, etc.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.