0

Is there a way to set a Python object attribute object.attribute to return a function or getter method?

For Example:

class CrossSection():
    def __init__(self):
        self.data = pd.Series([1,3,5,np.nan,6,8])

Now constructing a Panel() Object, I would like to have an attribute Panel.data that returns data from the underlying CrossSection Objects each time (preferably without duplicating the data):

class Panel():
    def __init__(self):
        # - Core Object - #
        self.xs = dict()
        self.xs[1] = CrossSection()
        self.xs[2] = CrossSection()

        # - Data Object - #
        self.data = self.find_data()

    def find_data(self):
        self.data = dict()
        for n in self.xs.keys():
            self.data[n] = self.xs[n].data
        return self.data

In the example above, there are two issues:

  1. the find_data() method runs only on __init__ but if any of the underlying CrossSections() change (or are loaded after __init__) then self.data wouldn't represent the underlying CrossSection() objects.
  2. self.data constructs a new dictionary.

However it does mimic the behaviour I would like:

p = Panel()
p.data

    {1: 0     1
1     3
2     5
3   NaN
4     6
5     8
dtype: float64,
 2: 0     1
1     3
2     5
3   NaN
4     6
5     8
dtype: float64}

Therefore,

  1. Is there a way that I can request Panel.data such that it updates based on the underlying self.xs dictionary of CrossSection() objects.
  2. Can Panel.data return a function over the underlying CrossSection() objects? [or is my only option to interface using class methods?]
sanguineturtle
  • 1,425
  • 2
  • 15
  • 29
  • a `dict` keyed by monotonically-increasing integers is a far more awkward data structure than a simple `list`. – roippi Mar 24 '14 at 02:20
  • Agreed - in my actual data they are referenced by a year integer and aren't always consecutive. I also store a year list for the keys. – sanguineturtle Mar 24 '14 at 02:22

1 Answers1

2

Is there a way to set a Python object attribute object.attribute to return a function or getter method?

It's the typical use case of http://docs.python.org/2/library/functions.html#property

Can Panel.data return a function over the underlying CrossSection() objects?

Do you explicitly store the list of CrossSection() objects?

x3al
  • 586
  • 1
  • 8
  • 24
  • Yes I store the CrossSection() objects in a dictionary referenced by year. That looks like what I need - Thanks for pointing me in the right direction! – sanguineturtle Mar 24 '14 at 02:20