I made a simple code to demonstrate and understand classes – however when I run this, my lists show that they are empty, containing “None” values instead of the strings that the user enters as names.
#Static methods do not require the object to be initiated. Can be remotely accessed from outside the function .
#Counting critters and remote access.
class Orc (object):
total = 0
def get_score (self):
print "The number of orcs the orc factory has made is",Orc.total
def __init__ (self):
Orc.total += 1
name = raw_input ("I am a critter by the name of:\n")
#Creating 10 Orcs
list = []
for i in range (4): list[i] = list.append(Orc.get_score(Orc()))
print "You have created 4 Orcs!" print "The name of your first orc is",list[0] print "The name of your fourth orc is", list[3]
There are a few errors in your code. First in the way you use lists. Second, in the way you call methods on your objects. The combination of errors explains why you have a list of
Noneat the end.List name
Don’t name a list
list. It is already the name of, well…, the list class, i.e. in Python you can domy_list = []ormy_list = list()with the exact same effect.You want to call your list something meaningful, like
orc_listList Insertion
orc_list.appenddoes what it says: it appends an element to the given list. However, it does not return anything. So what your code is doing isito 0appendat the end of the listNoneat indexiand thus overriding what you did in 3.iYou want to simply use
orc_list.append(...)Method Call
I imagine you are getting confused by the
selfargument. In a class, Python will automatically pass the instance you are working on as theselfargument. You don’t need to provide that argument.You want to write
This creates an
Orcobject, and then callsget_scoreon it. Python ‘injects’ theOrcinstance you have created intoget_scorefor you.Method Return
We’re now down to
which is equivalent to
The problem is that there is no
returnstatement inget_score. This means that python will returnNonewhen you call that method. Which means that you are appendingNoneto your list.You want to have
Static behaviour
If you really wanted to have a method not bound to an instance of the
Orcclass, you could use either a class method or a static method.In your case, you do not need to do anything to the class object, so your choice would be to use a static method.
You would declare
You would then call that method using
Orc.get_score()