Why does this work?

Phlip phlip_cpp at yahoo.com
Wed Mar 27 09:26:48 EST 2002


a.clarke11 wrote:

> Hi
> I defined a class, and made an instance. The class sis not have a
> def__init__() line. In the class, I defined a function  f(x) and an list
> object X.tiles. Why can I later call instancename.f, and
> instancename.tiles?
> I thought the class had to have a def__init__() line in it for this to
> work? I would be glad if somebody could spell this out for me, although
> it is working perfectly well in the finished program!
> The relevant code is:
> class Player:
> 
>  import random
>  Tiles=[]
>  Sound="click"
>  Win="yippee"
>  playlist=[]

Firstly, please push your code apart with more blank space, to make it 
readable.

>  def chooseTiles(x):

>   x.Tiles=[]

That is called a "magic member". (At least I call it that.) Members don't 
only declare in the __init__, they declare anywhere you say a reference to 
the object, a dot, the member name, an equals =, and a value.

MMs are a bad habit, because if later on you accidentally type...

        x.Tyles=[]

...you now have two members with similar names, and Python won't warn.

We have a style guideline to only declare members in the __init__. That 
does very little to help this problem, but we go Test-First with PyUnit so 
our risk is very low.

And we wrap all data members in get/set pairs, so the above would have been:

        x.setTiles([])

Because Magic Methods are impossible, we are covered.

-- 
  Phlip
           http://flea.sourceforge.net
  --  The plasma signature at the end of the
      wormhole is an approaching warbird  --



More information about the Python-list mailing list