Reputation: 903
This represents a simple class, that I have made to try and practice OOP.
import csv
import logging
class LoaderCSV:
def __init__(self, file):
self.file = file
if file is None:
logging.warning('Missing input file.')
def load(self):
with open(self.file) as f:
holder = csv.reader(f)
file_data = list(holder)
return file_data
What happens is when I call this class with:
data = LoaderCSV.load(input_file)
I get
line 14, in load
with open(self.file) as f:
AttributeError: 'str' object has no attribute 'file'
I must be messing something up, but can't understand what. My previous attempt worked just fine this way. I just don't understand why
self.file
does not pass the value, assigned to the argument, when it is defined under __init__
Upvotes: 0
Views: 84
Reputation: 1544
The problem is you're calling an instance method as a static method, so your filename is being passed in instead of self
. The proper way to do this would be like:
loader = LoaderCSV(input_file)
data = loader.load()
This will pass in loader
as the self
parameter, allowing you to access the file name in the object's file
field.
Check out the Python documentation on classes for more information.
Upvotes: 2
Reputation: 362167
You need to create the LoaderCSV
object first, then call the load
method on that object.
loader = LoaderCSV(input_file)
data = loader.load()
Upvotes: 1
Reputation: 59240
The way to use the instance method load
is to make an instance of your class, and then call the method on that class. Like this:
myloader = LoaderCSV(input_file)
data = myloader.load()
or succinctly:
data = LoaderCSV(input_file).load()
Upvotes: 0