0

I need variable instances that by default have tuple behavior. Initially it must be exactly (1,1) That's why I've created the class that inherits from the tuple class. But a new created object initially equals to (,) (not (1,1) as I need).

I have following code but it doesn't work properly as I want.

class FooClass(tuple):

    def __init__(self):
        self = (1,1)

I need that new created objects works like this:

t = FooClass() # t must be (1,1) now
t = t[:-1] + (t[-1]+1,)
#t now must be (1,2)

What I do wrong?

4

2 回答 2

3

您正在方法self内重新绑定__init__self在反弹之前不会改变引用的对象。您只需将局部变量指向一个新对象。

然而,元组是不可变的,它们的子类也是。在被调用的时候,你不能再改变 self了。__init__

您需要在__new__此处使用一种方法来影响实例的创建方式;__new__是构造函数,__init__是初始化器:

class FooClass(tuple):
    def __new__ (cls):
        return super(FooClass, cls).__new__(cls, (1,2))

演示:

>>> class FooClass(tuple):
...     def __new__ (cls):
...         return super(FooClass, cls).__new__(cls, (1,2))
... 
>>> t = FooClass()
>>> t[:-1] + (t[-1]+1,)
(1, 3)

请注意,最后一个表达式再次产生一个元组;切片对象仍然返回元组:

>>> type(t)
<class '__main__.FooClass'>
>>> type(t[:-1])
<type 'tuple'>

根据您要执行的操作,您可能需要覆盖一些容器方法

于 2013-09-05T10:31:13.607 回答
0

注意, self 是对对象的引用。通过做

self = (1, 1)

您只是将变量 self 分配给一个很快将被垃圾收集的新元组。Self 不是一个合适的 Python 关键字,你可以称它为“mike”或“something”

于 2013-09-05T10:31:05.437 回答