Create a str child (either int or float or tuple) that accepts kwargs

I need a class that behaves like a string, but also accepts extra ones kwargs. Therefore, I subclass str:

class Child(str):

    def __init__(self, x, **kwargs):
        # some code ...
        pass


inst = Child('a', y=2)
print(inst)

This, however, increases:

Traceback (most recent call last):
  File "/home/user1/Project/exp1.py", line 8, in <module>
    inst = Child('a', y=2)
TypeError: 'y' is an invalid keyword argument for this function

This is rather strange since the code below works without errors:

class Child(object):

    def __init__(self, x, **kwargs):
        # some code ...
        pass


inst = Child('a', y=2)

Questions:

  • Why do I have a different behavior when you try to subclass str, int, float, tuple, etc. compared to other classes such as object, list, dictetc.
  • How to create a class that behaves like a string but has extra kwargs?
+4
source share
1

__new__, __init__:

>>> class Child(str):
...    def __new__(cls, s, **kwargs):
...       inst = str.__new__(cls, s)
...       inst.__dict__.update(kwargs)
...       return inst
...
>>> c = Child("foo")
>>> c.upper()
'FOO'
>>> c = Child("foo", y="banana")
>>> c.upper()
'FOO'
>>> c.y
'banana'
>>>

. , __init__ , str, int, float:

__new__() , (, int, str ), . , .

+7

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


All Articles