0

I am trying to better understand classes. Suppose I have a class that handles data modifications, such as copying data and resampling data. In my case, the function resample requires the function duplicate since I want to modify a copy of the original data rather than the original data itself.

I've seen a similar question addressed here, though I was unable to apply those solutions to my case. I'm wondering if things like @classmethod are required because of posts like this.

import numpy as np
import random

class DataMods():

    def __init__(self, data):
        self.data = data

    def duplicate(self):
        if isinstance(self.data, np.ndarray):
            res = np.copy(self.data)
        else:
            res = self.data[:]
        return res

    def resample(self, nshuffles=0, struct=np.array):
        # resample copy of data instead of data
        data_dup = self.duplicate(self.data) # this is the problematic line
        size = len(data_dup)
        if isinstance(nshuffles, int):
            if nshuffles > 1:
                for idx in range(nshuffles - 1):
                    res = struct(random.sample(list(data_dup), size))
        else:
            raise ValueError("nshuffles ...")
        return struct(random.sample(list(res), size))

aa = np.array([1, 2, 3, 4, 5])
a2 = DataMods(data=aa).resample(nshuffles=5)
print(a2)
>> TypeError: duplicate() takes 1 positional argument but 2 were given

If I change the problematic line to:

data_dup = self.duplicate(data)

Then I get a different error:

NameError: name 'data' is not defined

I've tried a few different variations, but all were unsuccessful. What am I not understanding correctly?

  • 1
    `duplicate` only takes one argument, the implicit `self`. Hence the error message; you're also passing `self.data` to it, which makes a total of two arguments. Try `self.duplicate()`. Alternatively, make it a `@staticmethod` that takes `data` as a single argument, so it *doesn't* refer to `self`. – jonrsharpe Feb 13 '18 at 18:28
  • Thanks for that, got it to work using `data_dup = self.duplicate()`. Do you know if `@classmethod` is another way of doing this? –  Feb 13 '18 at 18:30
  • `@classmethod` also has an implicit argument, the class itself (usually named `cls`). But how would that solve your problem? You either need access to `self` for the instance data, in which case use an instance method, or have it passed in explicitly, in which case use a static method; in neither case do you need access to any class state. – jonrsharpe Feb 13 '18 at 18:31

0 Answers0