user3002315
user3002315

Reputation: 91

OO Black Jack Game - computing hand values

Running the program will cause an error message:

TypeError: unsupported operand type(s) for +=: 'int' and 'NoneType'

The problem is with the line value += values.get(card.get_rank)

I think there may be a problem with the get_rank method? Does it not return an integer?

ranks = ('A','2','3','4','5','6','7','8','9','10','J','Q','K')
values = {'A':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9,'10':10,'J':10,'Q':10,'K':10}
suits = ('Diamonds','Hearts','Clubs','Diamonds')
class Card:
    def __init__(self, suit, rank):
        self.suit = suit
        self.rank = rank
    def __str__(self, suit, rank):
        print (self.rank + 'of' + self.rank)
    def get_rank(self):
        return self.rank
class Hand:
    def __init__(self):
        self.hand = []
    def __str__(self):
        hand = ''
        for card in self.hand:
            hand = hand + str(card)
        return hand
    def get_value(self):
        value = 0
        aces = 0
        for card in self.hand:
            if card.get_rank == 'A':
                aces += 1
            value += values.get(card.get_rank)

            if (aces>0) and (value + 10 <= 21):
                value += 10
        return value

Upvotes: 2

Views: 155

Answers (1)

jonrsharpe
jonrsharpe

Reputation: 122116

values.get(card.get_rank) tries to use the instance method as the key for the dictionary. This is not a valid key in the dictionary, so dict.get() returns the default None.

Instead you want to call the method, and use the return value as the key:

value += values.get(card.get_rank())

or, as trivial getters and setters are unpythonic, just access the attribute directly:

value += values.get(card.rank)

Note that you can also pass a default to dict.get() to ensure you always get a sensible return value:

value += values.get(card.rank, 0)

Now if there is no value for that card rank in values, its value is assumed to be zero.


Also, it's not clear where values is coming from. I would suggest you make it a class attribute:

class Hand:

    VALUES = {...}

    ...

    def get_value(self):
        ...
            value += self.VALUES.get(card.rank, 0)
             ...

Or an explicit argument to get_value:

class Hand:

    ...

    def get_value(self, values):
        ...
            value += self.values.get(card.rank, 0)
            ...

Upvotes: 1

Related Questions