Andrius Andrius - 7 months ago 9
Python Question

Python - Exclusive attribute value for object?

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)?

Answer

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

class A(object):
    objs = []
    def __init__(self, one=None):
        self.one = one
        if self.one:
            if A.objs:
                A.objs[-1].one = None
            A.objs.append(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
Comments