0

If we have a instance variable which can be set either randomly or via a list input is it better to set the instance variable explicitly (via a function return) or as a side-effect of a function? E.i., which of the versions below is better?

class A():
   def __init__(self, *input):
      if input:
         self.property = self.create_property_from_input(input)
      else:
         self.property = self.create_property_randomly()

   @staticmethod
   def create_property_from_input(input)
      # Do something useful with the input. 
      return result
   
   @staticmethod
   def create_property_randomly():
      # Do something useful
      return result

or

class A():
   def __init__(self, *input):
      if parents:
         self.create_property_from_input(input)
      else:
         self.create_property_randomly()

   def create_property_from_input(self, input)
      # Do something useful with the input. 
      self.property = result
      # return None
   
   def create_property_randomly(self):
      # Do something useful
      self.property = result
      # return None

I think that in the first version, it is not strictly needed to set the two create_property-functions as static methods. However, since they do not need to know anything about the instance I thought it was more clear to do it that way. Personally, I tend to think that the first version is more explicit, but the use of static methods tend to make it look more advanced than it is.

Which version would you think is closer to best practices?

JezuzStardust
  • 222
  • 2
  • 10
  • This basically boils down to whether instance attributes should be initialized outside of `__init__`, and according to [PEP8](https://peps.python.org/pep-0008) the answer is no: https://stackoverflow.com/questions/19284857/instance-attribute-attribute-name-defined-outside-init – DeepSpace Sep 29 '22 at 09:48
  • So, does this mean that first version is to prefer since it explicitly sets the instance variables inside of __init__? Should I keep the two functions as static methods also then? – JezuzStardust Sep 29 '22 at 10:16

0 Answers0