[Tutor] Objects & Classes...
Chad Crabtree
flaxeater at yahoo.com
Mon Jan 17 19:59:15 CET 2005
Jack Cruzan wrote:
>class Character:
>
> def __init__(self, name = ' ', race = 'Human', magic = 'None'):
>
> self.name=name
>
> self.race=race
>
> self.magic=magic
>
>
I know your going to need some other stuff.
class NewCharacter(Character):
def __init__(self,stats,*args,**kwds):
super(Character,self).__init__(*args,**kwds)
self.stats=stats
super is a function that calls a specific function from a parent
class.
This way you can still use the previous __init__ code and then extend
it. *args represents a tuple of arguments of unspecified length or
type, **kwds is a dictionary of named arguments, like name='' like
above. That way you capture the keywords needed to pass to the
parent
class so that name race magic is still updated at class
instantiation.
This way you can extend classes. So you *could* subclass Character
as a
Dwarf, a Troll etc so that each class already knows about being a
Dwarf,
eg special abilities skill bonuses and such. If you don't understand
this, that's ok it took me quite a while. However once I got this it
made certain tasks much easier. I could figure out how to do
something,
then never need to think about how it works later in the project.
>def createChar(book):
>
> name = raw_input("Enter your character's name. ")
>
> race = int(raw_input("What race? (1: Human, 2: Elf, 3: Ork, 4:
Troll,
>
>5: Dwarf,)"))
>
> book[name] = race
>
>
>
try this (untested)
races={1:'Human',2:'Elf',3:'Ork',4:'Troll',5:'Dwarf'} #this is a
dictionary
book[name]=races[race]
print "The Name is " + name
print "The Race is " + book[name]
>def loadChar(book):
>
> import os
>
> filename = 'SRchargen.dat'
>
> if os.path.exists(filename):
>
> store = open(filename,'r')
>
> while store:
>
> name = store.readline().strip()
>
> race = store.readline().strip()
>
> book[name] = race
>
> else:
>
> store = open(filename, 'w')
>
> store.close
>
>
I'm not sure why this doesn't work, perhaps you should post what is
in
'SRchargen.dat'. You do know that this format will only work with
one
character? Do you get an error? If so post that traceback message.
Anyway good luck.
__________________________________
Do you Yahoo!?
Yahoo! Mail - now with 250MB free storage. Learn more.
http://info.mail.yahoo.com/mail_250
More information about the Tutor
mailing list