Why does this work?
Jim Dennis
jimd at vega.starshine.org
Wed Mar 27 13:57:07 EST 2002
In article <3CA1BB93.FC00D40D at pop.ntlworld.com>, 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:
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
instances.
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
> Tiles=[]
> Sound="click"
> Win="yippee"
> playlist=[]
> def chooseTiles(x):
> import random
> random.shuffle(Setup.r)
> x.Tiles=[]
> while len(x.Tiles)<7:
> l=0
> l=Setup.r.pop(random.uniform(1,len(Setup.r)))
> x.Tiles.append(l)
> x.Tiles.sort()
> playstring=[]
> Porky=Player()
> Porky.chooseTiles()
> Thanks in anticipation
> Tony
More information about the Python-list
mailing list