Найти - Пользователи
Полная версия: ООП,не понимаю почему не работает метод __str__(self)
Начало » Python для новичков » ООП,не понимаю почему не работает метод __str__(self)
1
m1cky
Написал мини-класс:
class Card(object):
"""Одна игральная карта"""
RANKS = ["A","2","3","4","5","6","7","8","9","10","J","Q","K"]
SUITS = ["c","d","h","s"]
def __init__(self,rank,suit):
self.rank = rank
self.suit = suit
self.total = Card.RANKS.index(self.rank) + 1
def __str__(self):
rep = self.rank + self.suit
return rep

class Hand(object):
"""Рука: набор игральных карт"""
def __init__(self):
self.cards = []
def __str__(self):
if self.cards:
rep = ""
for card in self.cards:
rep += (str(card) + " ")
else:
rep = "<пусто>"
return rep
def clear(self):
self.cards = []
def add(self,card):
self.cards.append(card)
def give(self,card,other_hand):
self.cards.remove(card)
other_hand.add(card)

class Deck(Hand):
"""Колода карт"""
def populate(self):
for suit in Card.SUITS:
for rank in Card.RANKS:
self.add(Card(rank, suit))
#print(Card(rank,suit))
#print(self.cards)
def shuffle(self):
import random
random.shuffle(self.cards)
def deal(self,hands,per_hand = 1):
for rounds in range(per_hand):
for hand in hands:
if self.cards:
top_card = self.cards[0]
self.give(top_card,hand)
else:
print("Нет больше карт")
Пытаюсь проверить работоспособность метода populate() и получаю полную ахинею:

ab = Deck()
ab.populate()
print(ab)
Выдаёт:

<пусто>
1) Объясните,пожалуйста, почему выдаёт всё время пусто?

2) Есть ли какой-нибудь метод-аналог __str__() чтобы задавать его именно для вывода свойств?Ну,например,ab.cards?Чтоб он не выдавал список


P.S. при print(ab.cards) выдает список объектов-карт класса Card,но печатать экземпляр класса Deck с помощью print не хочет (для этого писал __str__)
ab.cards имеет тип list
содержит 52 объекта
печать просто ab не хочет :)
везде выдаёт Object,Object,Object…
PooH
В Hand.__str__(self) ветку else поднимете до if, а то сейчас она у вас к for относится
Loop statements may have an else clause; it is executed when the loop terminates through exhaustion of the list (with for) or when the condition becomes false (with while), but not when the loop is terminated by a break statement. This is exemplified by the following loop, which searches for prime numbers:
s0rg
В коде ошибка
FishHook
self.cards = []
rep += (str(card) + " ")
Так больше не делай никогда!
rep="  ".join(cards)
m1cky
Всем спасибо!
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Powered by DjangoBB