简体   繁体   中英

Why does this Python code print nothing?

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?

Try initialize your string first, with some value:

# 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。

Try printing (self,x,y). You will see

('', ('utf-8', 'aaa'), {})

Therefore, in str.decode(self,*x,**y) , self is acting as the empty string.

When you initiate b1 = a() , it's almost the same as b2 = str() except that b2 doesn't have the bound method b() of class a . Hence, when you invoke b1.b(...) , it's the same as calling print str.decode(b1,...) or print str.decode(b2, ...)

b1 and b2 are the same in the way that they are both empty strings. Now take a look at what docs say about str.decode .

decode(...) S.decode([encoding[ ,errors ]]) -> object

 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. 

That means the third parameter (actually the second in the context of bound method ) is a sort of error type which would be ignored if it doesn't match any builtin (registered) type.

So when you call b1.b('utf-8', 'abc') which will be corresponding to b1.b([encoding], [error type]) . Python will translate it to print str.decode(b1, [encoding], [error type]) . Since b1 is empty and your "error type" which is 'abc' doesn't match any registered error type, python just prints out an empty string and ignores the given "error type."

If you try b = a('hello') and bb('utf-8', 'abc') , you will see that the output is hello and there is nothing to do with 'abc' . Moreover, if you try to provide one more parameter such as bb('utf-8', 'abc', 'xyz') , python will raise an error since str.decode() only accepts up to two arguments in the context of bound method .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM