继承python中的内置`str`类 [英] Inherit builtin `str` class in python

查看:76
本文介绍了继承python中的内置`str`类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用自定义类型继承 str 模块,但这样做会出错.

I am trying to inherit the str module with custom type, but while doing so gives error.

class MyStr(str):
    def __init__(self, word, idx: int=0):
        super().__init__()
        self._word = word
        self._idx = idx


if __name__ == '__main__':
    x = MyStr(word='Word', idx=1)
    print(x)

出现这个错误

Traceback (most recent call last):
File "C:/Users/admin/Desktop/xyz.py", line 9, in <module>
   x = MyStr(word='Word', idx=1)
TypeError: 'word' is an invalid keyword argument for this function

那么,如何使用自定义参数继承str模块.

So, How do inherit str module with custom parameters.

我已经尝试了这个方法来继承所有的方法和属性.

I have try this method to inherit all the methods and attributes.

class MyStr(str):

    def __new__(cls, *args, **kwargs):
        return str.__new__(cls)

    def __init__(self, word, idx: int=0):
        super().__init__()
        self._word = word
        self._idx = idx

    @property
    def idx(self):
        return self._idx

    @property
    def word(self):
        return self._word


if __name__ == '__main__':
    ms = MyStr(word='snake', idx=10)
    print(ms)

所以我期望输出为:-

Expecting Output:
    Str: snake

But this give this 
    Str: 

推荐答案

不要对字符串的值使用关键字参数.只需使用一个位置参数.函数签名将是 MyStr(s, idx=0),其中 s 是字符串的值.

Do not use a keyword argument for the string's value. Just use a single positional argument. The function signature will be MyStr(s, idx=0) where s is the value of the string.

(1) 在您的 __new__ 实现中,不要传递关键字参数.str.__new__ 不知道如何处理它.两个参数都将传递给 __init__.

(1) In your implementation of __new__ do not pass the keyword argument. str.__new__ will not know what to do with it. Both arguments will get passed to __init__.

(2) 在您的 __init__ 实现中,只需忽略第一个参数.它已经被 str.__new__ 函数用来初始化字符串.您需要做的就是将 idx 参数存储在一个新变量中.

(2) In your implementation of __init__ just ignore the first argument. It has already been used to initialize the string by the str.__new__ function. All you need to do here is to store the idx argument in a new variable.

(3) 去掉 .word 属性.您已经有一个字符串,因此 .word 属性不会添加任何内容.

(3) Just get rid of the .word property. You already have a string, so the .word property doesn't add anything.

新实例的行为就像一个字符串,并且拥有字符串的所有方法.它还具有属性 idx.

The new instance will behave like a string and will have all the methods of a string. It will also have the property idx.

class MyStr(str):
    def __new__(cls, s, idx=0):
        return super().__new__(cls, s)
        # less good style is: str.__new__(cls, s)

    def __init__(self, s, idx: int=0):
        super().__init__()
        self._idx = idx

    @property
    def idx(self):
        return self._idx

if __name__ == '__main__':
    ms = MyStr('snake', idx=10)
    print(ms, ms.idx)
    print(ms.upper())

# Output:
# snake 10
# SNAKE 

我基本上同意那些根据一般原则建议不要这样做的评论者(这很棘手,您的代码对其他人来说不容易理解).但它确实有效.

I basically agree with those commenters who advised against doing this on general principles (it's tricky and your code will not be easy to understand for someone else). But it does work.

这篇关于继承python中的内置`str`类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆