【发布时间】:2019-02-05 09:25:42
【问题描述】:
我正在尝试使用自定义类型继承 str 模块,但是这样做会出错。
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 模块。
我已经尝试过这种方法来继承所有的方法和属性。
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:
【问题讨论】:
-
你需要实现
__new__,这是首先调用的。 -
@jonsharpe 我像这样使用
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,但没有任何反应。 -
什么意思“什么都没发生”?您不再收到错误消息(这可能是一件好事)?您可能看不到任何东西,因为您的实例看起来像一个空字符串。
-
如果您不向
str.__new__传递任何参数,您的所有MyStr实例都将为空字符串。 -
这并不能说明您描述的问题,为什么您认为
ms没有继承方法?正如我和@Aran-Fey 所提到的,您对__new__的使用正在构建一个empty 字符串(带有一些额外的属性)。另请注意,如果word是您实际希望字符串具有的值,则无需将其存储为属性。
标签: python python-3.x oop