簡體   English   中英

str.format()問題

[英]str.format() problem

所以我創建了這個類,當x = 0時輸出'{0}',或者對x的每個其他值輸出'{1}'。

class offset(str):  
    def __init__(self,x):  
        self.x=x  
    def__repr__(self):
        return repr(str({int(bool(self.x))}))
    def end(self,end_of_loop):
    #ignore this def it works fine
        if self.x==end_of_loop:
            return '{2}'
        else:
            return self

我想做這個:
offset(1).format('first', 'next')
但它只返回我給x作為字符串的數字。 我究竟做錯了什么?

你的str子類沒有覆蓋format ,所以當你在其中一個實例上調用format時,它只使用從str繼承的那個,它使用self的“內在值為str ”,即你傳遞給offset()的任何字符串形式offset()

要更改該內在值,您可以覆蓋__new__ ,例如:

class offset(str):
    def __init__(self, x):
        self.x = x
    def __new__(cls, x):
        return str.__new__(cls, '{' + str(int(bool(x))) + '}')

for i in (0, 1):
  x = offset(i)
  print x
  print repr(x)
  print x.format('first', 'next')

發射

{0}
'{0}'
first
{1}
'{1}'
next

注意,如果通過覆蓋__new__ ,您已經確保實例的內部值為str是您想要的格式,則無需覆蓋__repr__

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM