5.1. Static and Dynamic

5.1.1. Static Fields

  • Fields created on class

  • Must have default values

  • Share state

Listing 5.78. Static Fields
class Astronaut:
    agency = 'NASA'


watney = Astronaut()
jimenez = Astronaut()

print(watney.agency)
# NASA

print(jimenez.agency)
# NASA

print(Astronaut.agency)
# NASA

5.1.2. Dynamic Fields

  • Fields created on instance

  • Do not share state

  • By convention initialized in __init__()

  • You can also initialize on living object directly

Listing 5.79. Dynamic fields
class Astronaut:
    def __init__(self, agency='NASA'):
        self.agency = agency


watney = Astronaut()
twardowski = Astronaut()

print(watney.agency)
# NASA

print(twardowski.agency)
# NASA

print(Astronaut.agency)
# Traceback (most recent call last):
#     ...
# AttributeError: type object 'Astronaut' has no attribute 'agency'

5.1.3. Static vs. Dynamic Fields

Listing 5.80. Static vs. Dynamic fields
class Astronaut:
    agency = 'NASA'


watney = Astronaut()
twardowski = Astronaut()
ivanovic = Astronaut()

# Print field
print(watney.agency)           # NASA
print(twardowski.agency)       # NASA
print(ivanovic.agency)         # NASA
print(Astronaut.agency)        # NASA

# Change field on a class
Astronaut.agency = 'ESA'

# Print field
print(watney.agency)           # ESA
print(twardowski.agency)       # ESA
print(ivanovic.agency)         # ESA
print(Astronaut.agency)        # ESA

# Change field on the instance
ivanovic.agency = 'Roscosmos'

# Print field
print(watney.agency)           # ESA
print(twardowski.agency)       # ESA
print(ivanovic.agency)         # Roscosmos
print(Astronaut.agency)        # ESA

# Change field on a class
Astronaut.agency = 'POLSA'

# Print field
print(watney.agency)           # POLSA
print(twardowski.agency)       # POLSA
print(ivanovic.agency)         # Roscosmos
print(Astronaut.agency)        # POLSA

5.1.4. Static or Dynamic?

Listing 5.81. Static Fields
class Astronaut:
    firstname = ...
    lastname = ...
Listing 5.82. Dynamic Fields
class Cosmonaut:
    def __init__(self):
        self.firstname = ...
        self.lastname = ...
Listing 5.83. Dynamic Fields
from dataclasses import dataclass


@dataclass
class GaganYatri:
    firstname: str = ...
    lastname: list = ...
Listing 5.84. Dynamic Fields
class Taikonaut:
    pass

t = Taikonaut()
t.firstname = ...
t.lastname = ...
Listing 5.85. Static Fields
class Taikonaut:
    pass

Taikonaut.firstname = ...
Taikonaut.lastname = ...
Listing 5.86. Static Fields
class Taikonaut:
    pass

Taikonaut.firstname = ...
Taikonaut.lastname = ...

t = Taikonaut()
print(t.__dict__)

5.1.5. Assignments

Todo

Create assignments