在自定义Python类中重写默认方法的简单方法?

在自定义Python类中重写默认方法的简单方法?,python,class,methods,overriding,Python,Class,Methods,Overriding,我有一个叫做Cell的类: class Cell: def __init__(self, value, color, size): self._value = value self._color = color self._size = size # and other methods... Cell.\u value将存储字符串、整数等(无论我使用该对象做什么)。我希望所有通常使用对象“值”的默认方法都使用。\u value

我有一个叫做Cell的类:

class Cell:

    def __init__(self, value, color, size):
        self._value = value
        self._color = color
        self._size = size

    # and other methods...
Cell.\u value
将存储字符串、整数等(无论我使用该对象做什么)。我希望所有通常使用对象“值”的默认方法都使用
。\u value
,以便我可以执行以下操作:

>>> c1 = Cell(7, "blue", (5,10))
>>> c2 = Cell(8, "red", (10, 12))
>>> print c1 + c2
15

>>> c3 = Cell(["ab", "cd"], "yellow", (50, 50))
>>> print len(c3), c3
2 ['ab', 'cd']

# etc.
我可以覆盖所有默认方法:

class Cell:

    def __init__(self, value, color, size):
        # ...

    def __repr__(self):
        return repr(self._value)

    def __str__(self):
        return str(self._value)

    def __getitem__(self, key):
        return self._value[key]

    def __len__(self):
        return len(self._value)

    # etc.

…但有更简单的方法吗?

您需要重载
\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu方法,以获得所需的
c1+c2

有关它们都是什么的信息,请参见。

如果我理解正确,您正在寻找将对象的方法委托给该对象的属性的简单方法

您可以通过定义装饰器来避免某些重复性:

def delegate(method, prop):
    def decorate(cls):
        setattr(cls, method,
            lambda self, *args, **kwargs:
                getattr(getattr(self, prop), method)(*args, **kwargs))
        return cls
    return decorate
然后,您可以为要委派的每个方法应用装饰程序:

@delegate('__len__', '_content')
@delegate('__getitem__', '_content')
class MyList(object):
    def __init__(self, content):
        self._content = content

spam = MyList([1,2,3,4,5])

len(spam) # prints "5"

spam[0] # prints "1"
您可能可以通过修改decorator以多个方法名作为参数来进一步简化它


如果希望类充当完整包装器,则可能会重写类的
\uuu getattr\uuu
方法,以便在失败之前检查包装的对象。这将在没有实际继承的情况下模拟子类的行为。

为什么一个整数,
self.\u value
能够通过一个键进行索引?你有没有试过取整数的长度?此外,这可能不应该是社区维基:没有人会因为这样回答而得到别人的分数,我们爱我们这里的一些分数。-1:这不应该是一个维基。@aaronmcmooth
self.\u value
可以保存任何数据类型,所以我希望所有可能的方法都可用。很抱歉设置此“社区维基”。我没有意识到残疾是不可逆的。现在我知道了。我认为重写
\uuuu getattr\uuuu
更接近我想要的,但是我也看到了decorator选项中的值。现在,我只需要理解
\uuuuuGetAttr\uuuuuuuuu
\uuuuuuuuuGetAttribute\uuuuuuuuu
之间的区别: