#🔒 Best Constructor Practice

18 messages · Page 1 of 1 (latest)

median pagoda
#

Hello folks.

Out of the below two approaches, which do you prefer and why?

Approach 1:

class Maze:
  def __init__(self, grid):
    # use the parameter
    self.grid = grid

    # number of rows in grid
    self.rows = len(self.grid)

    # number of columns in grid
    self.cols = len(self.grid[0])

Approach 2:

class Maze:
  def __init__(self, grid):
    # use the parameter
    self.grid = grid

    # number of rows in grid
    self.rows = len(grid)

    # number of columns in grid
    self.cols = len(grid[0])
undone obsidianBOT
#

Hey @median pagoda!

Please edit your message to use a code block

Add a py after the three backticks.

```py
print('Hello, world!')
```

This will result in the following:

print('Hello, world!')```
undone obsidianBOT
#

@median pagoda

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

slate viper
runic star
#

I prefer 2*, it makes it clear that the value is passed as parameter or defined in the method, and not defined somewhere else in the class.

#

Does that make sense?

#

@median pagoda

slate viper
runic star
#

True, init is sorta an exception, but it could be a class attribute

slate viper
#

I guess so. Here it’s fairly benign though but for a larger init I take your point

#

I’ve seen far worse code than this, so in perspective either of these are fine :) But yes marginally I would go with 2

median pagoda
#

Yes, that makes sense.

median pagoda
slate viper
#

I didn’t mean you - I meant I have seen far worse code than this in general

crude elm
#

It's just a trade off. The first is more concise, but the latter is more robust (e.g. if other code deletes a header row from self.grid, the code lines that refer to self.grid is still fine as it is), and if you rename grid, then you only have to change it twice.

If these are lists, it's probably a good idea to do self.grid = grid.copy(). And if I was feeling fancy, I'd make properties on self that dynamically update along with the rows and columns of self.grid.

median pagoda
undone obsidianBOT
#
Python help channel closed for inactivity

This help channel has been closed. Feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.