0

I have these two ways of setting default values of a parameter in an object: First one:

class Test():
    Weight = 12.5

    def __init__(self, weight = Weight):
        self.weight = weight


 Testing = Test()
 print("First testing: {}".format(Testing.weight))

and second one:

class Test2():
    Weight = 12.5

    def __init__(self, weight = None):
        if weight is None:
            self.weight = Test2.Weight

Testing2 = Test2()
print("Second testing: {}".format(Testing2.weight))

Both result in expected format that they will print 12.5. My question is, are these ways equivalent, is one of them faster than the other (my personal tip is that the first one will take less time to execute)? Which one do you prefer? and Is there any other maybe better way? Thank you very much

Mechatrnk
  • 101
  • 1
  • 13

3 Answers3

1

See this topic for a discussion on the evaluation of default arguments.

def __init__(self, weight = Weight) will only be evaluated once at function definition time, while Test.Weight will be evaluated every time. So in this case you'll see different results:

testing = Test()
Test.Weight = 42
testing2 = Test()
print(testing.weight, testing2.weight)
deceze
  • 510,633
  • 85
  • 743
  • 889
1

The two methods are not identical. In the first example, Test(None) would result in setting weight to None, while in the second example it would result in setting weight to Weight.

Besides of that, I would prefer the first method, especially if it's clear that floats are expected. It's just less to write. But if you have to avoid setting weight to None, a combination of both could be the way to go.

Regarding speed: I would not care about the extra few nanoseconds the second method will cost.

Edit: as pointed out by other answers, if you update Test.Weight, the default parameter will not get updated, but in the second example, you will always set the updated value. If that's a problem, use the second method.

Tobias Brösamle
  • 598
  • 5
  • 18
1

They are not if <class>.weight gets updated:

class Test1():
    Weight = 12.5

    def __init__(self, weight = Weight):
        self.weight = weight


testing = Test1()
print("First testing: {}".format(testing.weight))
Test1.Weight = 50
testing2 = Test1()
print("Second testing: {}".format(testing2.weight))

# First testing: 12.5
# Second testing: 12.5


class Test2():
    Weight = 12.5

    def __init__(self, weight = None):
        if weight is None:
            self.weight = Test2.Weight

testing = Test2()
print("First testing: {}".format(testing.weight))
Test2.Weight = 50
testing2 = Test2()
print("Second testing: {}".format(testing2.weight))
# First testing: 12.5
# Second testing: 50

The default argument gets evaluated once at the method creation, so in the first case, the default would stay 12.5, whatever happens to Test1.weight.

Thierry Lathuille
  • 23,663
  • 10
  • 44
  • 50