1

Let say I have this class:

class A(object):
 def __init__(self, one=None):
   self.one = one

So every time you create A object, you can assign one attribute. But only the last object assigned not false value gets to keep it.

For example:

a = A('a')
b = A('b')
c = A()
print a
print b
print c
----
None
b
None

Now these objects are also actual records (rows) in database, so those could be accessed later.

What could be a good pattern (if there is) to set such attribute dynamically (unsetting attribute for older objects)?

Andrius
  • 19,658
  • 37
  • 143
  • 243
  • Can't you just use the factory pattern? Then you could keep track of the last object that has one set and unset as necessary. – Schore May 04 '16 at 08:15
  • Keep a list of instances (see e.g. http://stackoverflow.com/q/328851/3001761) and use a property to implement your setting/unsetting logic (see e.g. http://stackoverflow.com/q/17330160/3001761). – jonrsharpe May 04 '16 at 08:16

1 Answers1

1

You could store an instance in a class variable and unset the previous one in the __init__.

class A(object):
    obj = None
    def __init__(self, one=None):
        self.one = one
        if self.one:
            if A.obj:
                A.obj.one = None
            A.obj = self
    def __str__(self):
        return str(self.one)

Result:

>>> a = A('a')
>>> b = A('b')
>>> c = A()
>>> print a
None
>>> print b
b
>>> print c
None
TigerhawkT3
  • 48,464
  • 6
  • 60
  • 97
  • @Andrius - Please note the edit here. I don't know why I initially wrote it to store a whole `list` when only the last one was needed. – TigerhawkT3 May 04 '16 at 08:39