Let us assume I have a basic object with a handful of self-relevant points of data.
class A(object):
def __init__(self, x, y, width, length):
self.x = x
self.y = x
self.width = x
self.length = x
And so we go on to instantiate several A
objects and shove them into a list, as programmers are wont to do.
Now let us assume that these objects need to be checked for a particular state every so often, but we needn't check them on every pass, because their state doesn't change particularly quickly. So a checking method is written somewhere:
def check_for_ticks(object_queue):
for obj in object_queue:
if obj.checked == 0 and has_ticks(obj):
do_stuff(obj)
obj.checked -= 1
Ah, but wait - it wasn't designed with obj.checked
attribute! Well no big deal, Python is kind and lets you add attributes whenever, so we change the method a bit.
def check_for_ticks(object_queue):
for obj in object_queue:
try:
obj.checked =- 1
except AttributeError:
obj.checked = 0
if obj.checked == 0 and has_ticks(obj):
do_stuff(obj)
This works, but it gives me pause. My thoughts are mixed, because while it's a functional attribute to give an object and it solves a problem, the attribute isn't really used by the object. A
will probably never modify its own self.checked
attribute, and it isn't really an attribute that it 'needs to know about' - it's just incredibly convenient to give it that attribute in passing.
But -- what if there are multiple methods that might want to flag an object? Surely one does not create the class with every attribute that some other method might maybe want to flag it for?
Should I be giving objects new attributes in this way? If I should not, what is the better alternative to just giving them new attributes?