Molitoris
Molitoris

Reputation: 1035

Variable assignment in the constructor

I have a question to the variable assignment in the constructor: I have a constructer which takes the argument 'context'. First, I assign this variable to a class variable. Second, I create another class which also takes 'context' as an argument.

To my question: Is it better to assignment the class variable (self.context) or the argument from the constructor (context) to the new created class?

class State():
    def __init__(self, context):
        self.context = context           
        self.diconnected = Disconnected(self.context)

or

class State():
        def __init__(self, context):
            self.context = context           
            self.diconnected = Disconnected(context)

Upvotes: 0

Views: 267

Answers (3)

molbdnilo
molbdnilo

Reputation: 66431

None is objectively "better"; you're passing the same object to Disconnected in any case.

Which one you write depends on which dependency you want to emphasize: that Disconnected has the same context as self (which also implies that self always has one), or that it has the context passed in as the parameter.

Upvotes: 0

pointerless
pointerless

Reputation: 753

This is really not going to effect your program execution time in any significant way in Python. The only situation this could matter is when multiple threads may be using this data. I'd always use the argument just in case.

Upvotes: 0

Alex Hall
Alex Hall

Reputation: 36033

The end result is the same. Disconnected(context) is just slightly shorter and faster.

Upvotes: 2

Related Questions