相关疑难解决方法(0)

从str或int继承

为什么我在创建一个继承自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)
Run Code Online (Sandbox Code Playgroud)

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

python string int inheritance new-operator

47
推荐指数
5
解决办法
2万
查看次数

在Python中对int进行子类化

我有兴趣在intPython 中继承内置类型(我使用的是2.5版),但是在初始化工作时遇到了一些麻烦.

这是一些示例代码,应该是相当明显的.

class TestClass(int):
    def __init__(self):
        int.__init__(self, 5)
Run Code Online (Sandbox Code Playgroud)

但是,当我尝试使用它时,我得到:

>>> a = TestClass()
>>> a
0
Run Code Online (Sandbox Code Playgroud)

在哪里我期待结果5.

我究竟做错了什么?到目前为止,谷歌并没有太大的帮助,但我不确定我应该寻找什么

python inheritance subclass python-2.5

46
推荐指数
2
解决办法
1万
查看次数

标签 统计

inheritance ×2

python ×2

int ×1

new-operator ×1

python-2.5 ×1

string ×1

subclass ×1