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
python oop class multiple-inheritance


source to share


No one has answered this question yet

See similar questions:

ten
Is partial inheritance possible from Python?

or similar:

5504
Does Python have a ternary conditional operator?
5231
What are metaclasses in Python?
4473
Calling an external command in Python
3790
How can I safely create a subdirectory?
3602
Does Python have a substring method "contains"?
2818
Finding the index of an element by specifying the list that contains it in Python
2332
Understanding Python super () with __init __ () methods
1731
Are static class variables possible in Python?
1518
Prefer composition over inheritance?
1066
Python class inherits object



All Articles
Loading...
X
Show
Funny
Dev
Pics