Class structuring and inheritance in Python

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 slot game. Ideally, I want to use methods and variables from classes CardGame

and Slot

. However, I hesitate to use the following structure (recombining a tree?):

class VidPoker(CardGame, Slot)

      

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

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

Is there a best practice, preferred way to structure classes in these situations?

EDIT

Several people have suggested: Is partial inheritance possible with Python?

I think a mixin method (the accepted answer) would be a good solution most of the time, but in some cases it will fail if the method uses a 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 you CardGame

have an immutable class variable num_decks

used by a method shuffle

. I wouldn't be able to call shuffle

from VidPoker

if it inherits Slot

.

+3


source to share





All Articles