Evrim
Evrim

Reputation: 55

Creating a Python class that holds its value as an upper case string doesn't work

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.

Upvotes: 0

Views: 500

Answers (2)

phihag
phihag

Reputation: 287915

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())

Upvotes: 2

mouad
mouad

Reputation: 70031

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'

Upvotes: 4

Related Questions