Easy way of overriding default methods in custom Python classes?

2024/9/30 3:34:32

I have a class called Cell:

class Cell:def __init__(self, value, color, size):self._value = valueself._color = colorself._size = size# and other methods...

Cell._value will store a string, integer, etc. (whatever I am using that object for). I want all default methods that would normally use the "value" of an object to use <Cell object>._value so that I can do:

>>> 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.

I could override all the default methods:

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.

...but is there an easier way?

Answer

If I understand you correctly, you're looking for an easy way to delegate an object's method to a property of that object?

You can avoid some of the repetitiveness by defining a decorator:

def delegate(method, prop):def decorate(cls):setattr(cls, method,lambda self, *args, **kwargs:getattr(getattr(self, prop), method)(*args, **kwargs))return clsreturn decorate

You can then apply the decorator for each method you want delegated:

@delegate('__len__', '_content')
@delegate('__getitem__', '_content')
class MyList(object):def __init__(self, content):self._content = contentspam = MyList([1,2,3,4,5])len(spam) # prints "5"spam[0] # prints "1"

You could probably simplify it further by modifying the decorator to take multiple method names as argument.

If you want your class to act as a full wrapper, you could probably override the class's __getattr__ method to check the wrapped object before failing. That would emulate the behaviour of subclasses without actual inheritance.

https://en.xdnf.cn/q/71133.html

Related Q&A

Return first non NaN value in python list

What would be the best way to return the first non nan value from this list?testList = [nan, nan, 5.5, 5.0, 5.0, 5.5, 6.0, 6.5]edit:nan is a float

How to subplot pie chart in plotly?

How can I subplot pie1 in fig, so it be located at the first position. this is how I am doing it but it doesnt work out import pandas as pdimport numpy as npimport seaborn as snsimport plotly.offline a…

Example of use \G in negative variable-length lookbehinds to limit how far back the lookbehind goes

In the pypi page of the awesome regex module (https://pypi.python.org/pypi/regex) it is stated that \G can be used "in negative variable-length lookbehinds to limit how far back the lookbehind goe…

Regex with lookbehind not working using re.match

The following python code:import reline="http://google.com" procLine = re.match(r(?<=http).*, line) if procLine.group() == "":print(line + ": did not match regex") els…

testing python multiprocessing pool code with nose

I am trying to write tests with nose that get set up with something calculated using multiprocessing.I have this directory structure:code/tests/tests.pytests.py looks like this:import multiprocessing a…

Python verify url goes to a page

I have a list of urls (1000+) which have been stored for over a year now. I want to run through and verify them all to see if they still exist. What is the best / quickest way to check them all and re…

Bokeh: Synchronizing hover tooltips in linked plots

I have two linked plots. When hovering, I would like to have a tooltip appear in both plots. I already use the linked selection with great success, but now I want to link the tooltips also.Below is an …

Pipe STDIN to a script that is itself being piped to the Python interpreter?

I need to implement an SVN pre-commit hook which executes a script that itself is stored in SVN.I can use the svn cat command to pipe that script to the Python interpreter, as follows:svn cat file://$R…

subprocess.call using cygwin instead of cmd on Windows

Im programming on Windows 7 and in one of my Python projects I need to call bedtools, which only works with Cygwin on Windows. Im new to Cygwin, installed the default version + everything needed for be…

Django Celery Received unregistered task of type appname.tasks.add

Following the documentation and the Demo Django project here https://github.com/celery/celery/tree/3.1/examples/djangoProject Structurepiesup2|piesup2| |__init__.py| |celery.py| |settings.py| |urls…