Eric Kim
Eric Kim

Reputation: 2698

Python, class attribute error

I have a set of code that looks like this:

class DataFilter:

    def __init__(self, csvData):
        # converts csv string data to float lists, if possible
        data = []
        for line in csvData:
            try:
                line = line.split(',')
            except:
                print(line)
                return

            for i in range( len(line) ):
                try:
                    line[i] = float(line[i])
                except ValueError:
                    pass
            data.append(line)
        self.data = data

    def find_depth_index(self, depth):
        for index, line in enumerate( self.data ):
            if line[1] > depth:
                return index

    def remove_above_depth(self, depth):
        index = self.find_depth_index( depth )
        return self.data[ index: ]

    def remove_beyond_depth(self, depth):
        index = self.find_depth_index(depth)
        return self.data[ :index ]

data = DataFilter(data).remove_above_depth(SURF_CASING_DEPTH)
print('-----------------------')
data = DataFilter(data).remove_beyond_depth(VERTICAL_SEC_DEPTH)

Then it give me an error:

  File "C:/Users/Eric Soobin Kim/PycharmProjects/untitled/RAPID_use_filtered_data.py", line 35, in remove_beyond_depth
    def remove_beyond_depth(self, depth):
  File "C:/Users/Eric Soobin Kim/PycharmProjects/untitled/RAPID_use_filtered_data.py", line 26, in find_depth_index
    def find_depth_index(self, depth):
AttributeError: 'DataFilter' object has no attribute 'data'

The thing that I don't understand is that, it ran without a problem for the line:

data = DataFilter(data).remove_above_depth(SURF_CASING_DEPTH)

but its not working for,

data = DataFilter(data).remove_beyond_depth(VERTICAL_SEC_DEPTH)

I think my first filtering somehow alters elements in __ini__(), but i don't know what's going on. Why is this happening, and how can i fix it?

Upvotes: 1

Views: 83

Answers (2)

Nathan majicvr.com
Nathan majicvr.com

Reputation: 1031

You've reassigned data to be equal to something other than what you want.

data = DataFilter(data).remove_above_depth(SURF_CASING_DEPTH)

This means that now you've lost the pointer to data that you once had. Might I suggest making a copy like

new_data = DataFilter(data).remove_above_depth(SURF_CASING_DEPTH)
new_data2 = DataFilter(data).remove_beyond_depth(VERTICAL_SEC_DEPTH)

This way you still have the reference to the old data variable

Upvotes: 1

Object has no attribute data because you didnt give it the attribute. atributes are defined by making writing: self.object = [] instead of: object = []

Upvotes: 0

Related Questions