python - Create child of str (or int or float or tuple) that accepts kwargs -
i need class behaves string takes additional kwargs
. therefor subclass str
:
class child(str): def __init__(self, x, **kwargs): # code ... pass inst = child('a', y=2) print(inst)
this raises:
traceback (most recent call last): file "/home/user1/project/exp1.py", line 8, in <module> inst = child('a', y=2) typeerror: 'y' invalid keyword argument function
which rather strange, since code below works without error:
class child(object): def __init__(self, x, **kwargs): # code ... pass inst = child('a', y=2)
questions:
- why different behavior when trying subclass
str
,int
,float
,tuple
etc compared other classesobject
,list
,dict
etc? - how can create class behaves string has additional kwargs?
you need override __new__
in case, not __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' >>>
see here answer why overriding __init__
doesn't work when subclassing immutable types str
, int
, , float
:
__new__()
intended allow subclasses of immutable types (like int, str, or tuple) customize instance creation. commonly overridden in custom metaclasses in order customize class creation.
Comments
Post a Comment