moonGuy
moonGuy

Reputation: 41

Is it bad practice to change a class' attributes in it's own methods?

Hey just some beginner looking for advice.

class Board():

    def __init__(self):
        self.x = 0
        self.y = 0
    
    def SelectSquare(self,direction):
        #based on some value from direction
        self.x += 1
        #or
        self.y += 1

        #return square at self.x and self.y

Given the above code, is it bad practice to create attributes that will change inside an object like this?

Upvotes: 3

Views: 2321

Answers (2)

trincot
trincot

Reputation: 350715

It is perfectly fine. It fits with the Object Oriented Programming paradigm, which says (Wikipedia):

A feature of objects is that an object's own procedures can access and often modify the data fields of itself

Just two remarks:

  • Use snake_case for your method names, not PascalCase

  • If a method mutates properties, then it might be better not to have it return something. When a coder calls this method being aware about the returned value, they may be surprised that there is also another, side effect.

    Decide whether the function should return something -- in which case it is often better not mutate the instance -- or else does not return something, in which case it is perfectly fine to mutate the instance. There are of course exceptions to this rule. The important thing here is that the caller should not be surprised by the "side effects".

Upvotes: 4

Mureinik
Mureinik

Reputation: 311796

This is not a bad practice. If your logic dictates changing an object's attributes, it makes perfect sense to have a method to handle that, as opposed to doing it in an unrelated piece of code, and thus breaking the principle of encapsulation.

Upvotes: 2

Related Questions