3

Suppose I have the following structure:

class CasinoGame
    self.expected_return

class CardGame(CasinoGame)
    self.deck
    def shuffle()
    def reset() # get a new deck and shuffle

class Slot(CasinoGame)
    self.credits
    def spin()
    def reset() # return credit to user, reset bonus progression

Now I want to introduce another class VideoPoker which is a card-based slot game. Ideally I want to use methods and variables from both CardGame and Slot classes. However, I'm hesitant to use the following structure (recombining tree?):

class VidPoker(CardGame, Slot)

I think it will be confusing to keep track of MRO and inheritance structure especially when I need to add more classes later, extending depth and width.

Ideally I want VidPoker to inherit Slot (video poker is technically a slot machine), but "borrow" functions from CardGame.

Is there any best practice, preferred way of structuring classes in these types of situation?

EDIT

A few folks suggested: Is it possible to do partial inheritance with Python?

I think mixin method (accepted answer) would be a good solution most of the time, but it will fail in certain cases where method uses class variable.

Example

# this works
class Class2(object):
    def method(self):
        print ("I am method at %s" % self.__class__)

class Class1(object): pass

class Class0(Class1):
    method = Class2.method

ob = Class0()
ob.method()

# this doesn't work
class Class2(object):
    s = 'hi'
    def method(self):
        print (self.s)

class Class1(object): pass

class Class0(Class1):
    method = Class2.method

ob = Class0()
ob.method()

Back to my example, suppose CardGame has an immutable class variable num_decks used by shuffle method. I wouldn't be able to call shuffle from VidPoker if it inherits Slot.

James Kang
  • 389
  • 1
  • 3
  • 8

0 Answers0