SkyWalker
SkyWalker

Reputation: 14317

What's the best approach to defer class attribute initialization?

I have the following OO use-case:

class SomeClass(object):

    def __init__(self, arg1):
        self.attr_now = arg1
        self.attr_later = None

    def compute(self):
        # do some lengthy computation ...
        self.attr_later = x # some result
        # continue work ... 

Is this an ideal approach to defer initialization of attribute attr_later or is there a better way? What I see is the type unsafety of the attr_later as it may change type during the lifespan of the enclosing instance ...

Upvotes: 0

Views: 254

Answers (1)

Kris
Kris

Reputation: 8873

Since you are talking about the OO use case, I think you must know about the access modifications you can do to protect the attribute for its value and type.

Think of this

class SomeClass(object):

    def __init__(self, arg1):
        self.__attr_now = arg1
        self.__attr_later = None

    @property
    def attr_later(self):
        return self.__attr_later

    def compute(self):
        # do some lengthy computation ...
        self.__attr_later = x # some result
        # continue work ... 

The instance variables can be prefixed with a __ for making it private to that instance. So you are sure, the variable cannot be changed from outside. More over, create a property for the variable, so that you can access the value from outside.

If you think, you want to set the value from outside, define a setter and control the incoming assignment - something like

@attr_later.setter
def attr_later(self, attr_val):
    if isinstance(attr_val,str):
        self.__attr_later = attr_val
    else:
        raise 
        # or do damage control

You are in control of your instance, if you properly encapsulate the properties. Hope this makes some sense

Upvotes: 2

Related Questions