tags:

views:

169

answers:

4
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?
+4  A: 

because you initialize b (as an object of a) with nothing as str.

rahmivolkan
Very confusing answer, especially given the multiple occurrences of "b". I think you meant to say "as an instance of a", and possibly "with an empty string as the initial value" or something like that.
Peter Hansen
i have been learning python for 2 days(a total of 2 hours) and I wrote what I think about the question in my way;As a result you are right, may be i had better not reply python questions after learning a lot :)
rahmivolkan
+8  A: 

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',) {}
#
The MYYN
+5  A: 

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.

unutbu
yes, always a helpful hint ...
The MYYN
+2  A: 

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 b.b('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 b.b('utf-8', 'abc', 'xyz'), python will raise an error since str.decode() only accepts up to two arguments in the context of bound method.