tags:

views:

43

answers:

1

Hi folks,

I was writing some python classes the other day, and created a class like this:

class Option:
 Name = ""
 Description = ""
 Criteria = {}

 def __init__(self, name,  descr):
  self.Name = name
  self.Description = descr

 def addCriteria(self,  cname,  ctype):
  ...

In my program, I was accessing the data in the class directly, i.e.:

cname = opt.Name

While this was a conscious decision, I know a lot of classes would have abstracted this as:

cname = opt.getName()

Should I have taken the time to abstract all the data and not allow direct access? What triggers when you would add access methods for class data?

Mike

+4  A: 

Even though this goes against anything you learn when doing OOP, I would suggest, that you defer the decision until it really turns out, that you need some "magic" to take place on attribut access. In Python, it is easy enough to refactor the class providing the attributes using the special property function:

class ItsMagic(object):

    _name = None

    def _get_name(self):
        return self._name

    def _set_name(self, new_name):
        self._name = new_name

    Name = property(_get_name, _set_name)


magic = ItsMagic()
magic.Name = "Foo"

This is transparent to the clients of this class, ie., they cannot usually tell (and should not care), whether the property reference is handled by providing access to the actual object attribute or by means of magic getter/setter functions, and it can be applied later (if it turns out to be required, that is).

Dirk