Reputation: 4758
I would like to know which one of the following two alternatives is better, or maybe more Pythonic:
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
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:
The first alternative is less verbose since a lot of self.
typing is avoided and the code is more readable.
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
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