相关疑难解决方法(0)

使用多个__init__参数对元组进行子类化

以下代码有效:

class Foo(tuple):

    def __init__(self, b):
        super(Foo, self).__init__(tuple(b))

if __name__ == '__main__':
    print Foo([3, 4])

$ python play.py 
Run Code Online (Sandbox Code Playgroud)

结果:

play.py:4: DeprecationWarning: object.__init__() takes no parameters
  super(Foo, self).__init__(tuple(b))
(3, 4)
Run Code Online (Sandbox Code Playgroud)

但不是以下内容:

class Foo(tuple):

    def __init__(self, a, b):
        super(Foo, self).__init__(tuple(b))

if __name__ == '__main__':
    print Foo(None, [3, 4])

$ python play.py 
Run Code Online (Sandbox Code Playgroud)

结果:

Traceback (most recent call last):
  File "play.py", line 7, in <module>
    print Foo(None, [3, 4])
TypeError: tuple() takes at most 1 argument (2 given)
Run Code Online (Sandbox Code Playgroud)

为什么?

python inheritance tuples subclass

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

Python,子类化不可变类型

我有以下课程:

class MySet(set):

    def __init__(self, arg=None):
        if isinstance(arg, basestring):
            arg = arg.split()
        set.__init__(self, arg)
Run Code Online (Sandbox Code Playgroud)

这可以按预期工作(用字符串而不是字母初始化集合).但是,当我想对set的不可变版本执行相同操作时,该__init__方法似乎被忽略:

class MySet(frozenset):

    def __init__(self, arg=None):
        if isinstance(arg, basestring):
            arg = arg.split()
        frozenset.__init__(self, arg)
Run Code Online (Sandbox Code Playgroud)

我可以实现类似的东西__new__吗?

python set immutability

13
推荐指数
1
解决办法
2528
查看次数

标签 统计

python ×2

immutability ×1

inheritance ×1

set ×1

subclass ×1

tuples ×1