【问题标题】:Creating a custom format specifier in __format__ method in python在 python 的 __format__ 方法中创建自定义格式说明符
【发布时间】: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


    【解决方案1】:
    NumberCard(1, Suit('Club', '♣'))
    

    所以,排名是一个整数

    你打电话给replace("%r", self.rank)

    错误提示replace() argument 2 must be str, not int

    在替换中使用str(self.rank)

    【讨论】:

      【解决方案2】:

      转换它?

      def __format__(self, format_spec):
          if format_spec == "":
              return str(self)
          else:
              result = format_spec.replace("%r", str(self.rank)) # stringify your int
              result = result.replace("%s", str(self.suit.symbol)) # symbol instead class name
              result = result.replace("%%", "%")
      

      替换适用于 replace(str,str) - 您不能使用 int 替换 str

      独库:https://docs.python.org/3.6/library/stdtypes.html#str.replace

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-11-15
        • 1970-01-01
        • 2014-09-13
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多