【发布时间】:2018-04-29 06:56:31
【问题描述】:
我通过在我的类中重写__format__() 方法来实现我自己的格式说明符。现在我遇到的麻烦是我收到了以下错误。是因为我不能将%s 用于除str() 之外的任何其他格式规范,还是我在这里做错了什么。
Traceback(最近一次调用最后一次): 文件“test.py”,第 66 行,在 print("庄家有 {0:%r of %s}".format(NumberCard(1, Club))) 文件“ch1.py”,第 24 行,格式 结果 = format_spec.replace("%r", self.rank).replace("%s", self.suit) TypeError: replace() 参数 2 必须是 str,而不是 int
class Card:
insure = False
def __init__(self, rank, suit):
self.suit = suit
self.rank = rank
self.hard, self.soft = self._points()
def __str__(self):
return "{rank}{suit}".format(**self.__dict__)
def __repr__(self):
return "{__class__.__name__}(suit={suit!r}, rank={rank!r})".format(__class__=self.__class__, **self.__dict__)
def __format__(self, format_spec):
if format_spec == "":
return str(self)
else:
result = format_spec.replace("%r", self.rank).replace("%s", self.suit)
result = result.replace("%%", "%")
return result
class NumberCard(Card):
def _points(self):
return int(self.rank), int(self.rank)
class Suit:
def __init__(self, name, symbol):
self.name = name
self.symbol = symbol
我将我的论点传递为
print("Dealer has {0:%r of %s}".format(NumberCard(1, Suit('Club', '♣'))))
【问题讨论】:
标签: python-3.x oop