Python 创建接受kwargs的str(或int、float或tuple)的子级
我需要一个行为类似字符串的类,但也需要额外的Python 创建接受kwargs的str(或int、float或tuple)的子级,python,python-3.x,parent-child,subclass,keyword-argument,Python,Python 3.x,Parent Child,Subclass,Keyword Argument,我需要一个行为类似字符串的类,但也需要额外的kwargs。因此,我将子类str: class Child(str): def __init__(self, x, **kwargs): # some code ... pass inst = Child('a', y=2) print(inst) 然而,这引起: Traceback (most recent call last): File "/home/user1/Project/exp1.py
kwargs
。因此,我将子类str
:
class Child(str):
def __init__(self, x, **kwargs):
# some code ...
pass
inst = Child('a', y=2)
print(inst)
然而,这引起:
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
问题:
- 为什么我在尝试将
、str
、int
、float
等子类与其他类(如tuple
、object
、list
等)进行分类时会得到不同的行为dict
- 如何创建一个行为类似于字符串但具有 额外的夸尔格
\uuuuu new\uuuuu
,而不是\uuuu init\uuuu
:
>>> 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'
>>>
有关在对不可变类型(如str
、int
和float
)进行子类化时重写\uuuu init\uuuu
不起作用的原因,请参阅:
\uuuu new\uuuu()
主要用于允许不可变类型的子类(如int、str或tuple)自定义实例创建。也是
通常在自定义元类中重写以自定义类
创造
可能是关于需要重写的
\uuuu str\uuuu
或\uuuuu unicode\uuuuu
方法
>>> 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'
>>>