nop = 0
patron = list
def createnew(firstname, lastname, phone, age, gender):
name = (lastname.lower() + ", " + firstname.lower())
patron.append(patrons(name, phone, age, gender))
nop += 1
class patrons():
number = 1
def __init__(self, name, phone, age, gender):
self.name = name
self.phone = phone
self.age = age
self.gender = gender
There's a couple of parts of my code for a program that holds information about library patrons. What I want to do is store all the members of the class (patrons) in a list (patron), I know the names are a little confusing, I wasn't really thinking, sorry about that. The problem which I am encountering is that when I run the createnew function, I receive an error which says "descriptor 'append' requires a 'list' object but received a 'patrons'" I was under the impression that I could store class objects in a list. Am I unable to do this? If I can do it, what do I have to change?
3 Answers 3
patron = list should probably be patron = list():
Calling list.append(1) reproduces an error similar to the one you mention:
In [1]: list.append(1)
TypeError: descriptor 'append' requires a 'list' object but received a 'int'
To understand the meaning of the error message, you might start by reading about how methods are descriptors. Also note that in Python2 unbound methods such as list.append must be called with an instance of the calling class (e.g. list). But that is mostly irrelevant to fixing your problem unless you are curious about the nature of the error.
patron = list makes patron equal to the built-in class list.
patron = list() makes patron an instance of the class list.
Comments
you should setup patron as
patron = list()
Unrelatedly, nop += 1 will throw an UnboundLocalError. Add global nop inside createnew More info here
1 Comment
As said before, list should be list() and you should give nop as an argument:
nop = 0
patron = list()
def createnew(firstname, lastname, phone, age, gender, nop):
name = (lastname.lower() + ", " + firstname.lower())
patron.append(patrons(name, phone, age, gender))
nop += 1
class patrons():
number = 1
def __init__(self, name, phone, age, gender):
self.name = name
self.phone = phone
self.age = age
self.gender = gender
1 Comment
nop += 1 and does not mutate the global variable