Search code examples
pythonpropertiesgetter-setter

When to store things as part of an instance vs returning them?


I was just wondering when to store things as part of a class instance versus when to use a method to return things. For example, which of the following would be better:

class MClass():

    def __init__(self):
        self.x = self.get_x()
        self.get_y()
        self.z = None
        self.get_z()

    def get_x(self):
        return 2

    def get_y(self):
        self.y = 5 * self.x

    def get_z(self):
        return self.get_x() * self.x 

What are the conventions regarding this sort of thing and when should I assign things to self and when should I return values? Is this essentially a public/private sort of distinction?


Solution

  • You can use the @property decorator:

    class MClass():
    
        def __init__(self):
            self.x = 2
    
        @property
        def y(self):
            return 5 * self.x
    
        #here a plus method for the setter
        @y.setter
        def y(self,value):
            self.x = y/5   
    
        @property    
        def z(self):
            return self.x * self.x 
    

    It's a good way of organizing yours accessors