Python, immutable type subclasses

I have the following class:

class MySet(set): def __init__(self, arg=None): if isinstance(arg, basestring): arg = arg.split() set.__init__(self, arg) 

This works as expected (initializing a set with the words of a string, not letters). However, when I want to do the same with an immutable version of the set, the __init__ method seems to be ignored:

 class MySet(frozenset): def __init__(self, arg=None): if isinstance(arg, basestring): arg = arg.split() frozenset.__init__(self, arg) 

Is it possible to achieve something like this with __new__ ?

+12
source share
1 answer

Yes, you need to override the special __new__ method:

 class MySet(frozenset): def __new__(cls, *args): if args and isinstance (args[0], basestring): args = (args[0].split (),) + args[1:] return super (MySet, cls).__new__(cls, *args) print MySet ('foo bar baz') 

And the result:

 MySet(['baz', 'foo', 'bar']) 
+12
source

Source: https://habr.com/ru/post/1201685/


All Articles