Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/324.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 创建接受kwargs的str(或int、float或tuple)的子级_Python_Python 3.x_Parent Child_Subclass_Keyword Argument - Fatal编程技术网

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'
>>>