Struggling with program

Michael Torrie torriem at gmail.com
Sun Feb 17 22:49:53 EST 2013


On 02/17/2013 07:29 PM, maiden129 wrote:
> I'm trying to do this assignment and it not working, I don't
> understand why...
> 
> This is what I have to do:
> 
> Write the definition of a class  Player containing: An instance
> variable  name of type  String , initialized to the empty String. An
> instance variable  score of type  int , initialized to zero. A method
> called  set_name that has one parameter, whose value it assigns to
> the instance variable  name . A method called  set_score that has one
> parameter, whose value it assigns to the instance variable  score . A
> method called  get_name that has no parameters and that returns the
> value of the instance variable  name . A method called  get_score
> that has no parameters and that returns the value of the instance
> variable  score . No constructor need be defined. can someone please
> help me?

While no one here is willing to do homework for someone else we do like
to help out however we can.

As Dave alluded to, python "instance variables" are called attributes
and typically are initialized in the the __init__(self, ...) method of
the class.  The "self" name, however, can be anything you want.  For
consistency, most python programmers use "self."

So your assignment is a bit misleading when it says a constructor is not
required, because if you want to initialize some instance attributes, it
has to be done in a method, usually the constructor, which in Python is
__init__.

"Instance variables" always need to be referred to with an explicit self
parameter.  This is always the first parameter of any method
declaration. Thus you would define things kind of like so:

---------------------
from __future__ import print_function #in case python2

class MyClass(object):
    def __init__(self, var2):
	# create instance attributes and assign them values
        self.instance_variable = 5
        self.instance_variable2 = var2

    def print_values(self):
        print("instance_variable is {0}, and instance_variable2 is
{1}".format(self.instance_variable, self.instance_variable2))

if __name__ == "__main__":
    c = MyClass(10); # this passes 10 to the __init__ method
    c.print_values() # note there is no self parameter passed;
                     # python passes "c" for you implicitly.
----------------------

If you run this python snippet you get this as output:

instance_variable is 5, and instance_variable2 is 10




More information about the Python-list mailing list