0

I have two approaches to initialize an object:

class Class1:
    def __init__(self):
        self.foo = None
        self.get_foo()
    
    def get_foo(self):
        # do complex stuff
        self.foo = something

class Class2:
    def __init__(self):
        self.foo = self.get_foo()
    
    def get_foo(self):
        # do complex stuff
        return something

Which one is the best approach according to Software Engineering and/or OOP best practices? Or maybe neither?

sevs
  • 73
  • 1
  • 6
  • Is `get_a()` always return the value of attribute `a`? Is/should be user able to set the attribute `a`? – buran Feb 04 '22 at 19:21
  • I prefer `Class2`. There is no reason to initialize it to None if you're about to initialize it on the next line. – Chrispresso Feb 04 '22 at 19:21
  • It looks like `self.a` should just be a `property` or `cached_property`. – Axe319 Feb 04 '22 at 19:22
  • @buran that should represent a complex operation, I'm gonna edit it to make it clearer. – sevs Feb 04 '22 at 19:24
  • I understand that it's probably [complex] calculation. I mean is it possible value of `a` change in a different way except from calculations in `get_a`. Check https://stackoverflow.com/q/2627002/4046632 and https://stackoverflow.com/q/6618002/4046632 – buran Feb 04 '22 at 19:29
  • 1
    Initializing `self.foo` to `None` only to immediately change its value is kind of pointless. Initializing `self.foo = None` until `self.get_foo` is called *later* makes more sense. That's a fairly common design, where a property `foo` waits until it is accessed to compute a value and save it to an underlying attribute `_foo` that can be retrieved on subsequent calls. – chepner Feb 04 '22 at 19:30

0 Answers0