0
class Foo(object):

    bar = {'a': None, 'b': None}

    def do_something(self):
        print self.bar['a']
        self.bar['a'] = 12

what I'd like to do is:

  1. when read from self.bar[xxx], I get the real value

  2. when write to self.bar[xxx], call a setter to do the real setting.

Here is a real world example:

class VoteMixin(object):

    self._vote_nums = {'up': None, 'down': None}

    def fetch_from_db(self):
        self._vote_nums = {} # set with values read from db

    @property
    def up_vote_nums(self):
        if self._vote_nums['up'] is None:
            self.fetch_from_db()
        return self._vote_nums['up']

    @property
    def down_vote_nums(self):
        # the same
        pass

    def up_vote(self):
        # update to db

        if self.vote_nums['up'] is None:
            self.fetch_from_db()

        self._vote_nums['up'] += 1

    def down_vote(self):
        # update to db

        if self.vote_nums['down'] is None:
            self.fetch_from_db()

        self._vote_nums['down'] += 1

the problem is, I don't want to check if self._vote_nums['up or down'] is None each time I want to write to it.

wong2
  • 34,358
  • 48
  • 134
  • 179
  • 2
    Then `bar` needs to not be a `dict`. – Ignacio Vazquez-Abrams Apr 08 '14 at 03:55
  • Use `@property`: http://stackoverflow.com/questions/6618002/python-property-versus-getters-and-setters Wait, I just realize that you want the key access... hmm... – justhalf Apr 08 '14 at 03:55
  • Or write a `set_bar` function that you pass the key and the value to. This is illogical based on your example, a real-world use case would probably help. – John Lyon Apr 08 '14 at 03:57
  • @jozzas I've updated with a real world example – wong2 Apr 08 '14 at 04:03
  • Duplicate of: http://stackoverflow.com/questions/6618002/python-property-versus-getters-and-setters apparently, since it's already answered there using `@uberProperty` that the answerer created. – justhalf Apr 08 '14 at 04:05

0 Answers0