为什么这个Python代码不打印什么?
class a(str):
def b(self,*x,**y):
print str.decode(self,*x,**y)
b=a()
b.b('utf-8','aaa') # This prints nothing, why?
尝试首先初始化你的字符串,具有一定的价值:
# classes should have capitalized names ...
class a(str):
def b(self,*x,**y):
print 'debugging: ', self, x, y
print str.decode(self, *x,**y)
if __name__ == '__main__':
b=a('aaa')
b.b('utf-8')
b=a()
b.b('utf-8')
# => output
# debugging: aaa ('utf-8',) {}
# aaa
# debugging: ('utf-8',) {}
#
因为你初始化b(作为a的一个对象)而没有str。
尝试打印(个体经营,X,Y)。你会看到
('', ('utf-8', 'aaa'), {})
因此,在str.decode(self,*x,**y)
,self
充当空字符串。
是的,总是有帮助的提示... – miku 2010-01-12 11:26:00
当您启动b1 = a()
,它几乎一样b2 = str()
除了b2
没有a
类的bound method
b()
。因此,当你调用b1.b(...)
,它是与调用print str.decode(b1,...)
或print str.decode(b2, ...)
b1
和b2
是它们都是空字符串的方式相同。现在看看有关str.decode
的文档。
解码(...) S.decode([编码[,错误]]) - >对象
Decodes S using the codec registered for encoding. encoding defaults to the default encoding. **errors** may be given to set a different error handling scheme. Default is 'strict' meaning that encoding errors raise a UnicodeDecodeError. Other possible values are 'ignore' and 'replace' as well as any other name registerd with codecs.register_error that is able to handle UnicodeDecodeErrors.
这意味着第三个参数(实际上是第二位的bound method
的上下文)是一种错误类型,如果它不匹配任何内建(注册)类型,将被忽略。
所以当你拨打b1.b('utf-8', 'abc')
这将对应b1.b([encoding], [error type])
。 Python会将其翻译为print str.decode(b1, [encoding], [error type])
。由于b1
为空,并且您的“错误类型”'abc'
与任何已注册的错误类型都不匹配,因此python只会输出一个空字符串并忽略给定的“错误类型”。
如果您尝试b = a('hello')
和b.b('utf-8', 'abc')
,您会看到输出为hello
,与'abc'
无关。此外,如果您尝试提供多个参数(如b.b('utf-8', 'abc', 'xyz')
),python将引发错误,因为str.decode()
只能在bound method
的上下文中接受最多两个参数。
非常令人困惑的答案,尤其是考虑到多次出现的“b”。我认为你的意思是说“作为一个实例”,可能“以空字符串作为初始值”或类似的东西。 – 2010-01-12 17:05:34