1

There is a code where variable is defined as follows:

class MoveSquareClass(object):

    # create messages that are used to publish feedback/result
    _feedback = TestFeedback()
    _result   = TestResult()

    def __init__(self):
    # code continues

My question what will happen when we create an instance of the class, will the variables be declared? I understand that defining the variables inside the constructor would simplify things but this was how the code was. Also should we call them using .init prefix? If yes, why?

1
  • 2
    The class attributes are defined as soon as the class is defined. Whether they should be class attributes or instance attributes depends on how the class will be used; it's impossible to say from this snippet. Commented Jan 8, 2020 at 16:38

1 Answer 1

1

The _feedback and _result objects are created once, when the MoveSquareClass class is created. They will be shared between all subsequent instances of MoveSquareClass. If they were created inside __init__ instead, they wouldn't be shared objects any more; each instance of MoveSquareClass would get its own instance of TestFeedback and TestResult. This could very well result in a significant change in behaviour - so you should be wary about changing it if you don't fully understand the code.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.