Newbie: Classes

ryan scott ryan.scott at sympatico.ca
Mon Oct 27 22:04:03 EST 2003


Michael Loomington wrote:
> This is taken from the tutorial:
> 
>>>>class Complex:
>>>
> ...     def __init__(self, realpart, imagpart):
> ...         self.r = realpart
> ...         self.i = imagpart
> 
> So this is a constructor correct because of the __init__ ?

Yes, this is the constructor for the Complex class


> What is the self mean exactly?  And if I create another def can that def see
> my r and i variables and can I call them?
> So I can do something like?
> 
> def real():
>     return r
> 
> In java you declare your variables outside of methods that's why I'm a
> little confused.
> 

The self refers to the specific instance of that class that you create.
So when you call a method on an instance, the self parameter represents 
the instance doing the calling.

For example,when you create the following objects
complex1 = Complex(3.0, -4.5)

complex2 = Complex(3.5, -5.6)

and then call
complex1.real(), it will return 3.0 and complex2.real() will return
3.5.

To use instance variables in your methods you have to append the 
variable with self and have self as a parameter.  So your real method 
would become

def real(self):
     return self.r




> The self just means its a constructor?  So really it has two parameters?

Yes

> 
> Also, I read somewhere you don't need to specify the parameters?  So how can
> you assign r and i to 0 if the user doesn't specify the parameters?
> 

> In java if you call the instance of a class it returns a string if you wrote
> a toString() method in that class.  How can I do that in python?

You can override the __str__ method.

def __str__(self):
    print "toString"


> 
> Thanks.
> 
> 
Ryan









More information about the Python-list mailing list