6.2. OOP Mutability

6.2.1. Rationale

  • Function and method arguments should not be mutable

6.2.2. Immutable Types

  • int

  • float

  • complex

  • bool

  • None

  • str

  • bytes

  • tuple

  • frozenset

6.2.3. Mutable Types

  • list

  • set

  • dict

6.2.4. Argument Mutability

Bad:

class Astronaut:
    def __init__(self, name, missions=[]):
        self.name = name
        self.missions = missions


watney = Astronaut('Mark Watney')
watney.missions.append('Ares 3')
print('Watney:', watney.missions)
# Watney: ['Ares 3']

twardowski = Astronaut('Jan Twardowski')
print('Twardowski:', twardowski.missions)
# 'Twardowski:' ['Ares 3']

Good:

class Astronaut:
    def __init__(self, name, missions=()):
        self.name = name
        self.missions = list(missions)


watney = Astronaut('Mark Watney')
watney.missions.append('Ares 3')
print('Watney:', watney.missions)
# Watney: ['Ares 3']

twardowski = Astronaut('Jan Twardowski')
print('Twardowski:', twardowski.missions)
# 'Twardowski:' []

6.2.5. Assignments

Todo

Create assignments