[Tutor] defining functions and classes

Dave Angel davea at ieee.org
Sat Jan 15 14:23:24 CET 2011


On 01/-10/-28163 02:59 PM, Brett Murch wrote:
> Hi everyone,
>
> I'm just starting to learn Python and am starting by creating a text
> game but am having trouble with classes and funtions. I want to create a
> class or function where someone creates a charater and has a choice of
> their name or os. This is what I have so far;
>
> class Administrator():
>      def Skills(name,os):
>          name = raw_input('What is your name')
>          os = raw_input('What is your os')
>          self.name = name
>          self.os = os
>
> Skills(name,os)
>
> I keep getting a syntax error on calling it. any ideas on what I'm doing
> wrong? Should it not be a class and should I just define it as a
> function or what?
>
> Thank you in advance
>
>

What previous experience in programming do you have?  You say you're a 
beginner in Python, but what other object orientation experience do you 
have?

I don't see any syntax error there.  Looks to me like a NameError.  When 
you get errors, you should copy/paste the whole error into your message, 
not just paraphrase it.  Anyway, the NameError would occur since Skills 
is not a valid global name, it's a method name within a class.  And if 
you got past that, then the same error would occur with the two 
arguments.  They're not defined anywhere either.

You're defining a class called Administrator.  That implies you're going 
to have many Administrator instances, and presumably each will have 
attributes called name and os.  If that's true, we can start refining.

The function to call to create an Administrator instance is called 
Administrator().  When you call Administrator(), it will implicitly call 
the __init__() method, not the Skills() method.  So you probably want to 
define such a method.

Once such an instance is created, you might call the Skills() method to 
change the original name and os for it.  But Skills() has the wrong 
method signature.  The first parameter of such a method is 'self', and 
you're missing that.  And the other two parameters are never used.

Perhaps you intended something like (untested):

class Administrator():
     def __init__(self, name="unknown", os="nevernever"):
         self.name = name
         self.os = os
     def change_skills(self):
         name = raw_input('What is your new name')
         os = raw_input('What is your new os')
         self.name = name
         self.os = os

admin1 = Administrator("Harry", "Windoze")
admin1.change_skills()


DaveA



More information about the Tutor mailing list