Jac*_*ing 6 python methods overriding class
我有一个名为Cell的课程:
class Cell:
def __init__(self, value, color, size):
self._value = value
self._color = color
self._size = size
# and other methods...
Run Code Online (Sandbox Code Playgroud)
Cell._value将存储字符串,整数等(无论我使用该对象).我想要通常使用对象的"值"的所有默认方法,<Cell object>._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.
Run Code Online (Sandbox Code Playgroud)
我可以覆盖所有默认方法:
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.
Run Code Online (Sandbox Code Playgroud)
......但有更简单的方法吗?
Ala*_*lum 11
如果我理解正确,你是否正在寻找一种简单的方法将对象的方法委托给该对象的属性?
您可以通过定义装饰器来避免某些重复性:
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
Run Code Online (Sandbox Code Playgroud)
然后,您可以为要委派的每个方法应用装饰器:
@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"
Run Code Online (Sandbox Code Playgroud)
您可以通过修改装饰器以将多个方法名称作为参数来进一步简化它.
如果您希望您的类充当完整包装器,您可以覆盖类的__getattr__方法以在失败之前检查包装对象.这将模拟没有实际继承的子类的行为.