The actor becomes an emotional athlete. The process is painful — my personal life suffers.
Al Pacino

I work with C# during the day.  At night, I am learning Python.  I try to apply my C# knowledge to coding in Python.  In C#, I use properties frequently.  Properties almost always have a getter method.  To write to a property, there is a setter method.

I created a Python class with a property but the setter never ran.  Finally, I found out why:  Something about new-style class in Python.  I needed to derive my classes from object, not the default parent class.

Wrong : class MyClass():

Right : class MyClass(object):

#!/usr/bin/env python

Simple container class

Michael Gillson

class ConfigInfo(object):
  def __init__(self, configFile):
  self.ConfigFile = configFile
  self.LargeFile = False
  self.Debug = False
  self.Verbose = False
  self.StopOnCopyError = False
  self._JoinString = ", "

  #Use this style for python 2.5

  #def _getJoinString(self):
    #return self._JoinString

  #def _setJoinString(self,value):
    #if value:
      #self._JoinString = value
      #self._JoinString = ""

  #JoinString = property(_getJoinString, _setJoinString)

  # Use this style for python 2.6 and later

  def JoinString(self):
    """Join String between fields for use in __repr__"""
    return self._JoinString
  def JoinString(self, value):
    if value:
      self._JoinString = value
      self._JoinString = ""

  def __repr__(self):
    return "ConfigFile = %s%sLargeFile = %s%sDebug = %s%sVerbose = %s%sStopOnCopyError = %s" \
    % (self.ConfigFile, self.JoinString, self.LargeFile, self.JoinString,
       self.Debug, self.JoinString, self.Verbose, self.JoinString, self.StopOnCopyError)

if __name__ == "__main__":
  configInfo = ConfigInfo("xyz.xml")
  print configInfo
  configInfo.JoinString = None
  print configInfo
  configInfo.JoinString = "\n"
  print configInfo

Tags: ,

Leave a Reply