A TYPICAL NEWBIE MISTAKE?

François Pinard pinard at iro.umontreal.ca
Sun May 14 21:59:49 EDT 2000


Courageous <jkraska1 at san.rr.com> writes:

> Over the last few weeks, I've taken to creating classes thusly:

> class MyClass
> 	i=0
> 	f=3.1
> 	s="str"
> 	ll=[]

> 	def __init__(...)...

The `i', `f', `s' and `ll' variables are common (that is: shared, or
allocated only once) between all objects having MyClass type.  You refer
to them using `self.i', `self.f', etc.

> class MyClass

> 	i=0
> 	f=3.1
> 	s="str"
> 	ll=[]

> 	def __init__()

> 		i=0
> 		f=3.1
> 		s="str"
> 		ll=[]

> Albeit, now that I understand everything, this seems a
> bit reduntant. :)

A few colons are missing above, at the end of the `class' and `def' lines.
It is a good idea to give code to Python at least once before publishing it,
just to ensure there is no trivial syntax errors.  You might have noticed,
also, that your definition for `__init__' lacks its usual `self' argument.

The `i', `f', etc.  within the `__init__' definition are strictly local
to `__init__', and do not exist once the routine has been executed.
Use `self.i', etc. within `__init__' (say), if you want variables that
are local to each particular instance.

-- 
François Pinard   http://www.iro.umontreal.ca/~pinard






More information about the Python-list mailing list