4.1. Static and Dynamic Fields

4.1.1. Static Fields

  • Fields created on class

  • Must have default values

  • Share state

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


watney = Astronaut()
jimenez = Astronaut()

print(watney.agency)
# NASA

print(jimenez.agency)
# NASA

print(Astronaut.agency)
# NASA

4.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 4.53. 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)
# AttributeError: type object 'Astronaut' has no attribute 'agency'

4.1.3. Static vs. Dynamic Fields

Listing 4.54. 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 the instance
ivanovic.agency = 'Roscosmos'

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

# 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

4.1.4. Static or Dynamic?

class Astronaut:
    firstname = ...
    lastname = ...
class Cosmonaut:
    def __init__(self, firstname, lastname):
        self.firstname = firstname
        self.lastname = lastname
class Taikonaut:
    pass

t = Taikonaut()
t.firstname = ...
t.lastname = ...
class Taikonaut:
    pass

Taikonaut.firstname
Taikonaut.lastname
from dataclasses import dataclass


@dataclass
class GaganYatri:
    firstname: str
    lastname: list

4.1.5. Assignments

Todo

Create Assignments