Home How to have one method reference another method from within the same class?
Reply: 0

How to have one method reference another method from within the same class?

user1846 Published in July 21, 2018, 6:11 am

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)
            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))
            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)
>> 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?

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.309077 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO