创建接受kwargs的str(或int、float或tuple)的子级

2024-04-16 17:23:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要一个行为类似于字符串的类,但也需要额外的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

这很奇怪,因为下面的代码没有任何错误:

class Child(object):

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


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

问题:

  • 为什么我在尝试将strintfloattuple等子类与objectlistdict等其他类相比较时会有不同的行为?你知道吗
  • 如何创建一个行为类似于字符串但具有 额外的夸尔格?你知道吗

Tags: 字符串selfchildobjectinitdefcodesome
1条回答
网友
1楼 · 发布于 2024-04-16 17:23:48

在这种情况下,您需要重写__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'
>>>

请参见here以了解为什么在对不可变类型(如strintfloat)进行子类化时重写__init__不起作用:

__new__() is intended mainly to allow subclasses of immutable types (like int, str, or tuple) to customize instance creation. It is also commonly overridden in custom metaclasses in order to customize class creation.

相关问题 更多 >