qTan
qTan

Reputation: 23

Dynamically set instance attribute in Python

I have a class with two instance attributes. For example:

class Test(): 
    def __init__(self, parameter):
        self.one = self.somefunction(parameter)
        self.two = 'somestring'

In the same class I define a function somefunction which will, accordingly to the above coding, be called at the time the object is created. While I tried this, I could set self.one when I return some value inside my somefunction(parameter), like:

def somefunction(parameter):
    return ...

However, this doesn't feel like best practice.What's the best way to set an initial value of an instance dynamically?

Upvotes: 1

Views: 2569

Answers (1)

Batman
Batman

Reputation: 8927

There's nothing wrong with what you've done, unless somefunction takes a long time to return. As a rule, you don't normally want object creation/instantiation to take a long time. If it takes a long time to calculate that attribute you should do it the first time the attribute is accessed. And that can be done with property getters.

import time

class Foo(object):

    def __init__(self, parameter):
        self._one = None
        self.two = "some_string"
        self._parameter = parameter

    @property
    def one(self):
        if self._one is None:
            self.one = self._some_method()
        return self.one

    def some_method(self):
         time.sleep(10)
         return sorted(self._parameter)

When you call foo.one Python will check to see if "protected" attribute is still None. If it is, then it will do the expensive function call. The next time you try to access it, it will use the saved value.

Upvotes: 1

Related Questions