1

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?

3
  • 1
    Is there a reason not to put the code inline in your init method? (Also, I assume you mean __init__ rather than init, ie a constructor for the Test class.) Commented Sep 9, 2018 at 14:54
  • There is no reason to put it not in init (I corrected my post). I thought about modularizing the code and calling methods instead of hardcoding it into the init method. Commented Sep 9, 2018 at 15:08
  • It doesn't improve the code to have some initialisation code as separate methods, because separate methods should have a reason for being called separately. @Batman's answer below discusses how to separate the code out for performance reasons without resulting in a separate method. Commented Sep 9, 2018 at 15:11

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.