Soldalma
Soldalma

Reputation: 4758

Do I pass copies of arguments or the arguments themselves to functions within __init__?

I would like to know which one of the following two alternatives is better, or maybe more Pythonic:

  1. Use __init__ arguments directly as arguments of functions called within __init__:

    def class A(object):
        def __init__(self, x):
            self.x = x # I would like to do this anyway
            self.y = foo(x)
            # More code
    
  2. Use __init__ attributes that are copies of arguments as arguments of functions called within __init__:

    def class B(object):
        def __init__(self, x):
            self.x = x # I would like to do this anyway
            self.y = foo(self.x)
            # More code
    

The classes A and B should behave identically. However:

  1. The first alternative is less verbose since a lot of self. typing is avoided and the code is more readable.

  2. The second alternative may be more robust to further changes in the code.

Which one of A or B is better? Or perhaps it does not matter?

Upvotes: 0

Views: 84

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1123032

It matters very little. Not having to type out self is nice, and Python won't have to do an attribute lookup.

However, if self.x is a property that in some way transforms the value when setting or getting, then you have no choice, depending on wether or not you need to use the original x or the transformed self.x.

Upvotes: 2

Related Questions