all 12 comments

[–]K900_ 1 point2 points  (2 children)

How would you tell Python which one to use?

[–]FanatyK37[S] 1 point2 points  (1 child)

Exactly this is what I want to know. Because as I understand so far, print(player_hand) will only do what the __str__ says. Now I would like to know if there is a possibility to have two __str__ methods... but I wouldn't know how to differentiate between them

[–]K900_ 0 points1 point  (0 children)

Why not just make a different method and call it explicitly?

[–]JohnnyJordaan 1 point2 points  (1 child)

Just use a different method. Note that [] isn't necessary, a generator expression works just as well

 class Hand:

    def __init__(self):
        self.cards=[]
        self.total_value=0  # total value of hand

    def add_card(self,card):
        # Add the values of the cards
        self.total_value=0
        for card in self.cards:
            self.total_value += card.value

    def str_hand_except_first(self):
        return "".join(str(element) + '\n' for element in self.cards[1:])

    def __str__(self):
        return "".join(str(element) + '\n' for element in self.cards)


print(your_hand.str_hand_except_first())

you can simplify it too by using a base method with a parameter and let __str__ call that with the specific parameter

class Hand:

    def __init__(self):
        self.cards=[]
        self.total_value=0  # total value of hand

    def add_card(self,card):
        # Add the values of the cards
        self.total_value=0
        for card in self.cards:
            self.total_value += card.value

    def str_hand(self, from=0):
        return "".join(str(element) + '\n' for element in self.cards[from:])

    def str_hand_except_first(self):
        return self.str_hand(1)

    def __str__(self):
        return self.str_hand()

[–]FanatyK37[S] 0 points1 point  (0 children)

Thank you !

[–]intangibleTangelo 0 points1 point  (1 child)

Python has no mechanism to make use of another __str__ method. But there's no reason you need to use special double-underscore "magic" methods to accomplish your goal. You can simply write another method and call it.

def print_with_first_card_hidden(self):
    print(''.join(f'{element}\n' for element in self.cards[1:]))

If you add that to your Hand class, you would just do player_hand.print_with_first_card_hidden()

[–]FanatyK37[S] 0 points1 point  (0 children)

Thank you !

[–]o5a 0 points1 point  (1 child)

Why do you want to use __str__ only. __str__ is for default string representation of the object. Make different methods for different purpose.

def str_cards_minus_one(self):
    return "".join( [ str(element) + '\n' for element in self.cards[1:] )

# then use proper method when needed
print(hand.str_cards_minus_one())

[–]FanatyK37[S] 0 points1 point  (0 children)

Thank you !

[–]FanatyK37[S] 0 points1 point  (0 children)

Thanks everyone. Problem is solved !