Note that there are some explanatory texts on larger screens.

plurals
  1. POPython: preferred way to handle large number of attributes that might not exists?
    text
    copied!<p>EDIT: The original problem involves PyQt and matplotlib and the real question is too complicated to explain, so I tried to simplify it and it didn't really work out. But from the replies I learned the actual problem might lie somewhere else than what I originally thought. I guess this is what learning to program is about.</p> <p>Thanks everyone!</p> <hr> <p>I'm facing a stylistic problem that bothers me. I tried to make is as general as possible to be helpful to others as well. Consider the following class:</p> <pre><code>class Values(object): def __init__(self): self.first_attr = None self.second_attr = None self.third_attr = None self.fourth_attr = None def set_first(self, data): self.first_attr = data def set_second(self, data): self.second_attr = data def set_third(self, data): self.third_attr = data def set_fourth(self, data): self.fourth_attr = data def add_to_three(self): attrs = ( self.first_attr, self.second_attr, self.third_attr, ) self._add_one(attrs) def add_to_two(self): attrs = ( self.second_attr, self.fourth_attr, ) self._add_one(attrs) def _add_one(self, attrs): for attr in attrs: if attr: attr += 1 </code></pre> <p>We have a class of values. The class can have a total of 4 attributes of different values. Each value can be set with a setter (didn't use decorators to simplify things).</p> <p>There are also two methods that have a tuple of attributes whose value should be increased. These values are determined before run time. </p> <p>We also have a method "add_one" that adds one to those attributes that it receives if those attributes are set. Otherwise nothing should happen.</p> <p>Now let's create a couple instances and set some values</p> <pre><code>first_values = Values() first_values.set_second = 5 first_values.add_to_three() second_values = Values() second_values.set_first = 2 second_values.set_third = 4 second_values.add_to_two() </code></pre> <p>This works fine, because the "add_one" method checks if each attribute is set.</p> <p>But what if I have 50 attributes? I don't like the idea of setting them all to None. Also, I don't like the idea of explicitly writing the tuples in those add_to_ methods.</p> <p>What would be the most proper way to handle this if there are lots of attributes by changing only the Values class?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload