Created
March 4, 2015 05:28
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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