Subclass str: where is the problem?

harold dadapapa at googlemail.com
Mon Apr 24 09:05:07 EDT 2006


pascal.parent at free.fr schrieb:

> Hello, can anybody explain/help me:
>
> Python 2.4.2 (#2, Sep 30 2005, 21:19:01)
> [GCC 4.0.2 20050808 (prerelease) (Ubuntu 4.0.1-4ubuntu8)] on linux2
>
>
> class Upper(str):
>   def __new__(cls, value):
>     return str.__new__(cls, value.upper())
>
> u = Upper('test')
> u
> 'TEST'
> type(u)
> <class '__main__.Upper'>
> u = Upper('')
> u
> ''
> type(u)
> <class '__main__.Upper'>
>
>
> All seems to be ok...
>
> class MyObject(object):
>   def __init__(self, dictionary = {}):
>     self.id = dictionary.get('id', '')
>   def __setattr__(self, attribute, value):
>     value = type(value) is type('') and Upper(value) or value
>     object.__setattr__(self, attribute, value)
>
> m = MyObject({'id': 'test'})
> m.id
> 'TEST'
> type(m.id)
> <class '__main__.Upper'>
> m = MyObject()
> m.id
> ''
> type(m.id)
> <type 'str'>
>
> Why is m.id a str ?

Because Upper(value) will be False in the line
>     value = type(value) is type('') and Upper(value) or value
and thus, you assign value itself to value again.
rewrite it for exmaple in this way:

   def __setattr__(self, attribute, value):
     if type(value) is type('') :
         value = Upper(value)
     object.__setattr__(self, attribute, value)




More information about the Python-list mailing list