I never got formal OOP instruction, and just kinda stumbled my way through the basics in python, but am at a crossroads. When dealing with an instantiated class object, is it better to assign attributes via methods, or have the methods just return the values? I've read a lot about not letting the object's state get out of whack, but can't figure out the best way. Here's a simple example:
import magic
class Histogram():
def __init__(self,directory):
self.directory = directory
# Data Option 1
def read_data(self):
data = []
file_ref = open(self.directory,'r')
line = file_ref.readline()
while line:
data.append(line)
line = file_ref.readline()
return data
# Data Option 2
def set_data(self):
data = []
file_ref = open(self.directory,'r')
line = file_ref.readline()
while line:
data.append(line)
line = file_ref.readline()
self.data = data
# Hist Option 1
def build_histogram(self):
data = self.read_data()
# It's not important what magic.histogram does.
self.histogram = magic.histogram(data)
# Hist Option 2
def get_histogram(self,data):
return magic.histogram(data)
# Hist Option 3 - this requires self.get_data() to have already run.
def build_histogram_2(self):
self.histogram = magic.histogram(self.data)
So Data Option 1 forces the user to either call that and store it somewhere to use in conjunction with Hist Option 2 or store it in self.data to use with Hist Option 3. Data Option 2 lets you use Hist Option 3, but you still have had to already run set_data.
So my real question is, for a class with methods to do different things, that often CAN but don't HAVE to be chained together, how should I write it? Implicitly setting attributes and risk getting the state messed up? Return variables and let the "User" set them? Have getters for the attributes that my methods use, and if the attributes don't exist handle that somehow?
Please let me know if you need better explanation, or another example or anything.
__init__, even if it's withNone, so you can see all attributes at once.