I have a class in which a method first needs to verify that an attribute is present and otherwise call a function to compute it. Then, ensuring that the attribute is not
None, it performs some operations with it. I can see two slightly different design choices:
class myclass(): def __init__(self): self.attr = None def compute_attribute(self): self.attr = 1 def print_attribute(self): if self.attr is None: self.compute_attribute() print self.attr
class myclass2(): def __init__(self): pass def compute_attribute(self): self.attr = 1 return self.attr def print_attribute(self): try: attr = self.attr except AttributeError: attr = self.compute_attribute() if attr is not None: print attr
In the first design, I need to make sure that all the class attributes are set to
None in advance, which can become verbose but also clarify the structure of the object.
The second choice seems to be the more widely used one. However, for my purposes (scientific computing related to information theory) using
try except blocks everywhere can be a bit of an overkill given that this class doesn't really interact with other classes, it just takes data and computes a bunch of things.