4
\$\begingroup\$

This code works by taking my user input and correctly pulling the information I'm giving it.

I'm having difficulty understanding the implementation of methods in classes. I'm pretty sure I'm not doing this the correct way. Can anyone show me the way it should be done?

class prog_setup:


 def __init__(self):
  """Initiates the below modules/variables."""

  self.get_starlist()
  self.get_InputKey()
  self.define_listsANDarrays()  
  self.determine_normalizationpoint()
  self.create_fobs_fobserr()
  #self.calculate_taumag()
  self.search_DUSTYmodels()
  self.calculate_chi2()
  self.delete_null_components()
  self.dust_whittet_sub()

 def get_starlist(self):
  """Imports the list of stars that you would like information on."""

  self.star_list=np.array([])

  try:
   get_star_list=raw_input('Input pathname of the list of stars to be studied: ')
   incoming_stars=open(get_star_list,'rb')
   for line in incoming_stars:
     x=line.split()
     self.star_list=np.append(self.star_list,x) #Appends the individual star-IDs to the empty array star_list.
   print 'Stars imported successfully.'
  except IOError:
   print 'Star import unsuccessful. Check that the star catalog file-path is correct. Program exiting now.'
   sys.exit()
  self.indices_of_star_list=range(len(self.star_list))


def get_InputKey(self):
 """Imports the Input (.inp) file. Historically, InputUttenthaler.inp. Allows for definition
 of parameters which are utilized later in the script."""

 input_script=raw_input('Pathname of .inp file: ')
 InputKey=[]
 self.band=''
 self.Ak_scalefactor=''
 try:
  with open(input_script) as input_key:
    for line in input_key.readlines():
     x=[item for item in line.split()]
     InputKey.append(x)
    if InputKey[0][0]=='1' or InputKey[0][0]=='2':  #Checks to see if .inp file is valid or not by checking the first row/column which should be 1 or 2.
     print 'Your .inp file was successfully imported'
    else:
     print 'Your .inp file import failed. Check the validity of your file.\n Program exiting now.'
     sys.exit()
 except IOError:
  print 'The .inp file import was unsuccessful. Check that your file-path is valid.\n Program exiting now.'                                
  sys.exit()

The entire code is longer; I just put in the first two methods to give an example of what my structure looks like.

\$\endgroup\$
5
  • \$\begingroup\$ Your indentation really should be more than 1 space each. Having it at 1 makes it unreadable. It should be at a minimum of 3 in any structured language really. Though for Python, it should be 4. \$\endgroup\$ – Jeff Mercado Aug 10 '13 at 0:03
  • 1
    \$\begingroup\$ Hard to tell from the snippet you provide, but it looks like you're simply trying to put all of your main programme code in a series of methods in a class. These functions don't seem to have much connection to each other, so why put them together in a class rather than just have them as free-standing functions? A class is usually used to create objects of a certain type, but what kind of object would prog_setup be? \$\endgroup\$ – Stuart Aug 10 '13 at 0:03
  • \$\begingroup\$ Having said all that, it might sometimes be useful to wrap a load of functions together in a class just to keep them separate from the rest of the code, and if that's all you are trying to do, this seems basically okay. \$\endgroup\$ – Stuart Aug 10 '13 at 0:03
  • \$\begingroup\$ @Stuart Originally this was someone else's code that was really hard to follow. I don't know much about python so I thought I'd try to rewrite it using classes. Reading more I've come to realize that I probably don't need to use classes, but in my ignorance I thought I had to to use the functions this way. If I used them without a class what would need to change? And yes, I'm aware that my indentation is not up to standards. I'm using eclipse and it didn't copy/paste over to the site too well. \$\endgroup\$ – Matt Aug 10 '13 at 0:10
  • \$\begingroup\$ Wow, methods are more methods with no arguments and no return values. That's what you would call a "stateful monster". I wonder, Is this kind of OOP still encouraged? \$\endgroup\$ – tokland Aug 10 '13 at 7:35
3
\$\begingroup\$

If you decide to implement this without using a class you can simply write:

def get_starlist():
    ...
def get_inputkey():
    ...

if __name__ == "__main__":
    get_starlist()
    get_input_key()
    define_lists_and_arrays()  
    determine_normalization_point()
    create_fobs_fobserr()
    search_DUSTY_models()
    calculate_chi2()
    delete_null_components()
    dust_whittet_sub()

But if you find that some of your functions are sharing data a lot you may want to attach them to a class, or pass instances of a class (objects) between the different functions. It's hard to say more without knowing what you're trying to do.

\$\endgroup\$
1
  • \$\begingroup\$ Cool. The functions essentially work linearly; the second function takes info from the first function, third from second, etc. It's not completely linear but for the most part that's how I'd characterize the essence of what I've written (having not shown everything). I think I can figure it out from here. Thanks for the help and clarification. \$\endgroup\$ – Matt Aug 10 '13 at 0:31
0
\$\begingroup\$

If your methods don't use any members write the as static methods

class ProgSetup(object):
   @staticmethod
   def getStarlist(x):
       pass

Some more tipps:

  • all classes should inheritance from object
  • please use more spaces for identidation
  • dont put _ in your variable/methodnames except for constants like THIS_IS_MY_CONSTANT
  • write your varibale names out, don't write short function/variable names
\$\endgroup\$
2
  • 2
    \$\begingroup\$ Using _ in variable and method names is standard in python \$\endgroup\$ – Stuart Aug 10 '13 at 0:52
  • 1
    \$\begingroup\$ @Quonux - please read PEP8. Using underscores to separate words IS the guideline for everything except for class names. So your getStarlist method should be get_star_list. As for the inherit from object, this is unnecessary since Python 3.0 but it is probably a good idea until the 2.x branches fall out of use. \$\endgroup\$ – D.Shawley Aug 10 '13 at 15:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.