Why does this work?
jimd at vega.starshine.org
Wed Mar 27 19:57:07 CET 2002
In article <3CA1BB93.FC00D40D at pop.ntlworld.com>, a.clarke11 wrote:
> 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
> 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:
You have the right to a constructor (def __init__()). If you do
not have the skill or time to type in your own constructor one will
be inherited into your class for you. You have the right to remain
silent and Python will just do "the right thing(TM)" for you.
A class is a template for creating objects. Objects, in Python, are
namespaces containing members (variables) and methods (functions)
(*and* containing linkages to parent classes through inheritance).
So instance.f() and instance.tiles are instantiated into your
objects because they were part of the template. Note that Tiles,
Sound, and playlist from your example (below) are all *class members*
rather than instance members. In other words they are shared by all
That's probably not what you want. You probably want playlist (at
least) to be specific to each player (though your code is far to
confusing for me to know what you're trying to do). Normally the
__init__() (constructor) for a player in a game would initialize
instance specific things like his or her "name" (or initials),
"color" (or icon or "piece" (a la Monopoly) or other designator),
and any initial score, tokens, money, "stats" or whatever.
> class Player:
> import random
> def chooseTiles(x):
> import random
> while len(x.Tiles)<7:
> Thanks in anticipation
More information about the Python-list