Style Q: Instance variables defined outside of __init__
Terry Reedy
tjreedy at udel.edu
Tue Mar 20 02:43:13 EDT 2018
On 3/19/2018 1:04 PM, Irv Kalb wrote:
> However, there is one warning that I am seeing often, an > I'm not sure about how to handle it. The warning I see is:
>
> "Instance attribute <instance variable name> defined outside of __init__ ..."
Style checkers are notorious for sometimes giving bad advice and being
overly opinionated.
I think a claim that in all programs all attributes should be set *in*
__init__, as opposed to *during* initialization, is wrong. All
attribute setting is side-effect from a functional view (and usually
'bad' to a functionalist). There is no reason to not delegate some of
it to sub-init functions when it makes sense to do do. There is good
reason to do so when it makes the code easier to understand *and test*.
Example: the IDLE's options setting dialog. Until last summer, it was
one class* with at perhaps a thousand lines of initialization code (with
no automated test). To me, the dictate that they should have all been
in the __init__ function is absurd. Fortunately, there were about 9
subsidiary functions.
* We split off a class for each tab, but keep the separate functions to
create the tab page widgets and load them with current values.
> The following is a simple example. I am creating a card class that I am using to build card games with PyGame.
> class Card():
>
> BACK_OF_CARD_IMAGE = pygame.image.load('images/backOfCard.png')
>
> def __init__(self, window, name, suit, value):
> self.window = window
> self.suit = suit
> self.cardName = name + ' of ' + suit
> self.value = value
> fileName = 'images/' + self.cardName + '.png'
> self.image = pygame.image.load(fileName)
> self.backOfCardImage = Card.BACK_OF_CARD_IMAGE
>
> self.conceal()
>
> def conceal(self):
> self.faceUp = False
>
> def reveal(self):
> self.faceUp = True
If the single line is all these functions do, I *might* suggest getting
rid of them. But this is really a separate issue.
--
Terry Jan Reedy
More information about the Python-list
mailing list