[Tutor] Methods that return instances of their own class?
David Perlman
dperlman at wisc.edu
Thu Oct 15 17:45:31 CEST 2009
Oh my goodness, it really is that easy! I guess I assumed that was
too simple to work. Silly me. Thanks Andre!
On Oct 15, 2009, at 10:31 AM, Andre Engels wrote:
> On Thu, Oct 15, 2009 at 5:14 PM, David Perlman <dperlman at wisc.edu>
> wrote:
>> I'm trying to figure out how to define a class so that its
>> instances have a
>> method that return a different object of the same class.
>>
>> In particular, I'm trying to run a simple prisoner's dilemma game,
>> and I
>> want to make a "game" object that has a method which returns the
>> "game"
>> object with the payoffs reversed; that is, the payoff matrix from
>> the other
>> player's point of view. Basically a kind of transpose which is
>> specific to
>> this application.
>>
>> class Payoffs(list):
>> def __init__(self, value=None):
>> list.__init__(self)
>> if value==None: # use a default prisoner's dilemma
>> value=[[(3,3),(0,5)],
>> [(5,0),(1,1)]]
>> self.extend(value)
>>
>> def __repr__(self):
>> l1="Your Choice: Cooperate Defect\n"
>> l2="My choice: -------------------------\n"
>> l3="Cooperate | (% 3d,% 3d) | (% 3d,% 3d) |\n" % (self[0]
>> [0][0],
>> self[0][0][1], self[0][1][0], self[0][1][1])
>> l4=" ----------------------- \n"
>> l5="Defect | (% 3d,% 3d) | (% 3d,% 3d) |\n" % (self[1]
>> [0][0],
>> self[1][0][1], self[1][1][0], self[1][1][1])
>> l6=" -------------------------\n"
>> return l1+l2+l3+l4+l5+l6
>>
>> def transpose(self):
>>
>> And that's where I'm at. How can I have the transpose method
>> return another
>> Payoffs object? Here's the beginning of it:
>>
>> def transpose(self):
>> trans=[[(self[0][0][1],self[0][0][0]),
>> (self[1][0][1],self[1][0][0])],
>> [(self[0][1][1],self[0][1][0]),
>> (self[1][1][1],self[1][1][0])]]
>>
>> But now "trans" is type list, not type Payoffs. I don't know how
>> to get it
>> into a Payoffs object so that the transpose will have my other new
>> methods.
>>
>>
>> Thanks very much. I searched for answers but I'm not sure what
>> this would
>> be called, which made it hard to find.
>
> I may be thinking too simple, but isn't this just:
>
> def transpose(self):
> trans=[[(self[0][0][1],self[0][0][0]), (self[1][0][1],self[1][0]
> [0])],
> [(self[0][1][1],self[0][1][0]), (self[1][1][1],self[1]
> [1][0])]]
> return Payoffs(trans)
>
>
> --
> André Engels, andreengels at gmail.com
--
-dave----------------------------------------------------------------
Unfortunately, as soon as they graduate, our people return
to a world driven by a tool that is the antithesis of thinking:
PowerPoint. Make no mistake, PowerPoint is not a neutral tool —
it is actively hostile to thoughtful decision-making. It has
fundamentally changed our culture by altering the expectations
of who makes decisions, what decisions they make and how
they make them. -Colonel T. X. Hammes, USMC
More information about the Tutor
mailing list