python - 从 str 或 int 继承

标签 python string inheritance integer new-operator

为什么我在创建继承自 str(或也继承自 int)的类时遇到问题

class C(str):
   def __init__(self, a, b):
     str.__init__(self,a)
     self.b = b

C("a", "B")

TypeError: str() takes at most 1 argument (2 given)

如果我尝试使用 int 而不是 str,也会发生同样的情况,但它适用于自定义类。我需要使用 __new__ 而不是 __init__?为什么?

最佳答案

>>> class C(str):
...     def __new__(cls, *args, **kw):
...         return str.__new__(cls, *args, **kw)
... 
>>> c = C("hello world")
>>> type(c)
<class '__main__.C'>

>>> c.__class__.__mro__
(<class '__main__.C'>, <type 'str'>, <type 'basestring'>, <type 'object'>)

由于__init__是在对象构造完成后调用的,所以修改不可变类型的值已经来不及了。注意 __new__ 是一个类方法,所以我调用了第一个参数 cls

here了解更多信息

>>> class C(str):
...     def __new__(cls, value, meta):
...         obj = str.__new__(cls, value)
...         obj.meta = meta
...         return obj
... 
>>> c = C("hello world", "meta")
>>> c
'hello world'
>>> c.meta
'meta'

关于python - 从 str 或 int 继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2673651/

相关文章:

python - Django 导入/导出到多个模型(外键)

c# - 解析变量 URI(RegEx、Uri、字符串函数?)c#

c++ - 将 std::string 分配给未终止的 char 数组时的预期行为?

c++ 数据对齐/成员顺序和继承

c++ - 为什么我不能访问作为参数传递给函数的基类的 protected 成员变量?

python - 使用 _mysql 修复 SQL 注入(inject)

python - 我的 Python 搜索代码的效率如何

python - 突出显示 panda 框架中具有 nan 值的所有行

java - 如何使用 Java 中的函数和方法循环读取字符串

objective-c - 强制子类在 Objective-C 中调用其父类(super class)方法