Skip to content

Instantly share code, notes, and snippets.

@lebedov
Created March 4, 2015 05:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lebedov/a4e6cd7b4f34ff72f0a6 to your computer and use it in GitHub Desktop.
Save lebedov/a4e6cd7b4f34ff72f0a6 to your computer and use it in GitHub Desktop.
How to create a class with an attribute that provides its own __getitem__() method.
#!/usr/bin/env python
"""
How to create a class with an attribute that provides its own __getitem__()
method (similar to pandas.DataFrame.ix).
"""
class Indexer(object):
def __init__(self, data):
if not hasattr(data, '__getitem__') or not hasattr(data, '__setitem__'):
raise ValueError('cannot create indexer for specified data')
self._data = data
def __getitem__(self, x):
return self._data[x]
def __setitem__(self, k, v):
self._data[k] = v
class DataClass(object):
def __init__(self, data):
self._data = data
self._ix = Indexer(self._data)
@property
def ix(self):
return self._ix
if __name__ == '__main__':
import numpy as np
d = DataClass(np.random.rand(10))
print d.ix[0:5]
d.ix[0:5] = 1
print d.ix[0:5]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment