Chris
Chris

Reputation: 31206

implementing python set logic (as in get and set)

So I have a class,

import numpy as np
class MyClass:
    def __init__(self):
       self.means = np.zeros(5)

And I have functions that expect an ndarray object...yet I have function calls I need to integrate my code with that set my object's mean to a list. Once that happens, everything breaks.

I need a way to force the class to set the incoming list as an ndarray. It seems like this is possible, reviewing the __set__ and __setattrib__ in the python documentation...but after reading the documentation, I am still mystified as to how to get the desired behavior.

What I want is to ensure that when other code says,

MyClass.means = [0,0,0,0]

the means get set to: np.array([0,0,0,0])

Upvotes: 0

Views: 79

Answers (1)

RemcoGerlich
RemcoGerlich

Reputation: 31250

Use a property setter:

class MyClass(object):
    def __init__(self):
        self._means = np.zeros(5)

    @property
    def means(self):
        return self._means  # Note the underscore

    @means.setter
    def means(self, value):
        # Convert to np array before setting
        self._means = np.array(value)

Upvotes: 3

Related Questions