[Tutor] Methods that return instances of their own class?

Andre Engels andreengels at gmail.com
Thu Oct 15 17:31:36 CEST 2009


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


More information about the Tutor mailing list