10.2. Attributes

10.2.1. About

  • Attributes are also known as "Properties" or "Fields"

  • snake_case name convention

  • Attributes store information (state) for instances

  • Access field values using dot (.) notation

  • Attributes should be defined only in __init__() method (covered in Initializer Method)

property
attribute
field
state

Variable inside the class.

10.2.2. Dynamic Attributes

Listing 203. Dynamic attributes
class Temperature:
    pass


temp = Temperature()
temp.kelvin = 10

print(temp.kelvin)
# 10
Listing 204. Dynamic attributes
class Astronaut:
    pass


astro = Astronaut()
astro.first_name = 'Jose'
astro.last_name = 'Jimenez'

print(f'My name... {astro.first_name} {astro.last_name}')
# My name... Jose Jimenez
Listing 205. Dynamic attributes
class Iris:
    pass


setosa = Iris()
setosa.features = [5.1, 3.5, 1.4, 0.2]
setosa.label = 'setosa'

print(setosa.label)
# setosa

sum(setosa.features)
# 10.2
Listing 206. Accessing not existing attributes
class MyClass:
    pass


my_instance = MyClass()
print(my_instance.xxx)
# AttributeError: 'MyClass' object has no attribute 'xxx'

10.2.3. Get all dynamic fields and values

  • obj.__dict__

Listing 207. __dict__ - Getting dynamic fields and values
class Iris:
    pass


flower = Iris()
flower.sepal_length = 5.1
flower.sepal_width = 3.5
flower.petal_length = 1.4
flower.petal_width = 0.2
flower.species = 'setosa'

print(flower.__dict__)
# {'sepal_length': 5.1,
#  'sepal_width': 3.5,
#  'petal_length': 1.4,
#  'petal_width': 0.2,
#  'species': 'setosa'}

10.2.4. Assignment

10.2.4.1. Data Modeling

English
  1. Model the data using classes

  2. Create instances for each record

  3. How many classes are there?

  4. How many instances are there?

  5. Print all fields from each instance

Polish
  1. Zamodeluj dane za pomocą klas

  2. Stwórz instancje dla każdego wpisu

  3. Jak wiele klas możemy wyróżnić?

  4. Jak wiele instancji możemy wyróżnić?

  5. Wypisz wszystkie pola każdej z instancji

Input
Jan, Twardowski, 1961-04-12
Mark, Watney, 1969-07-21
ESA, European Space Agency, Europe
NASA, National Aeronautics and Space Administration, USA
POLSA, Polish Space Agency, Poland
The whys and wherefores