'Best Practice in Python: Class Object with helper variables - delete helpers after use

I want to have a Class with only one argument to it. Based on that argument a couple of calculations should take place aiming at setting a specific attribute for the Class. Other attributes won't be needed afterwards and I would like to delete them within the Class. What's the best approach?

Simplified Example:

class Sportsteam:
    def __init__(self, members):
        self.members = members # members will be a list
        self.num_members = len(self.members) # helpler variable: how many team members are in the sportsteam?
        self.rooms = math.ceil(self.num_members/2) # how many doubles will be needed in a hotel?

I want to delete the instance variable num_members because it won't be needed afterwards. I want that to be done within the class/object, so I do not need a separate line with del instance.num_members within my script for each instance.

Please note that variable assigning is more complex with a lot of conditions in the original use case. Calculation without the helper-variable would work in the example above, but would be really annoying in the use case.



Solution 1:[1]

As @monk pointed out, also local variables can be assigned within the __init__ statement. For above example the use of a helper variable would therefor be:

class Sportsteam:
    def __init__(self, members):
        self.members = members # members will be a list
        num_members = len(self.members) # helper variable: how many team members are in the sportsteam?
        self.rooms = math.ceil(num_members/2) # how many doubles will be needed in a hotel?

In this case instance.num_members does not exist.

I was researching for an answer to my question with different keywords for quite a while, but neither came to a solution nor to an example which showed that possibility

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 thuettel