0

Why doesn't this work?

>>> class A (unicode):
...     def __init__ (self, value):
...         super(unicode, self).__init__(str(value).upper())
...
>>> assert A('hello') == u'HELLO'

Traceback (most recent call last):
  File "<pyshell#39>", line 1, in <module>
    assert A('hello') == u'HELLO'
AssertionError
>>>

I know that without the init method initializing the object would default to the unicode classes init method (thank you MRO) and I know that my init method is the one being called, however it doesn't seem to want to work. Even when I add an extra line and explicitly set the value of the value parameter to upper it still doesn't want to work.

Although I can (and probably will have to) define the repr and str special classes in order to get the desired effect, I'm a little curious as to why this doesn't work.

Thanks in advance.

Evrim
  • 55
  • 2

2 Answers2

4

unicode are immutable object use __new__ instead of __init__:

class A (unicode):
    def __new__ (cls, value):
       return unicode.__new__(cls, str(value).upper())

print A('hello')
u'HELLO'
Community
  • 1
  • 1
mouad
  • 67,571
  • 18
  • 114
  • 106
2

Instead of super(unicode, self), you probably want super(A, self) - the former is object.__init__.

Additionally, since unicode objects are immutable, __init__ does nothing. Instead of the regular initialization with __init__ (which would also prevent interning), the constructor you want to override is __new__:

class A (unicode):
    def __new__(cls, value):
        return super(A, cls).__new__(cls, str(value).upper())
phihag
  • 278,196
  • 72
  • 453
  • 469
  • +1, there's no 'probably' about it. `super` sure can be confusing. – SingleNegationElimination Jul 14 '11 at 16:15
  • @phihag, I can understand the first part, in fact I usually use super(self.__class__, self). I think I understand the second part... because unicode objects are immutable, the value is actually set when the instance is being created (hence __new__) not after it has been created and is being initialized. Thanks. – Evrim Jul 14 '11 at 17:17