Newbie: Classes

Dietrich Epp dietrich at zdome.net
Sun Oct 26 22:12:07 EST 2003


On Oct 26, 2003, at 6:27 PM, 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__ ?
> 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?

A good resource is the tutorial, good reading for starting out:
http://python.org/doc/current/tut/tut.html

Yes, the __init__ makes this  a constructor.  'self' is the object you 
are constructing, like 'this' in C (Java?).

> So I can do something like?
> def real():
>     return r

'r' isn't a variable... it's a part of self.  Try:

def real(self):
     return self.r

But this is a bad example, because if you want the value of 'r' you 
could just access it directly (fields aren't generally private in 
Python).

> In java you declare your variables outside of methods that's why I'm a
> little confused.

In Python you don't have to declare your variables or fields.  In fact, 
in Python, you don't have to declare anything.

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

The 'self' is the object.  There are no hidden parameters in Python.  
This has its pros and cons, for example it lets you add another method 
to a class (or instance) dynamically.

> 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?

You need to specify any parameter without a default.  So, in...

__init__(self,r,i)

...you need to supply the r and i parameters (self is supplied 
automatically), but in...

__init__(self,r=0,i=0)

...you can call Complex(), Complex(1), Complex(i=0.74), ad nauseam.

> 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?

Use __str__...

def __str__(self):
     return str(self.r) + ' + ' + str(self.i) 'j'






More information about the Python-list mailing list