1. Classes and Instances

1.1. Object Paradigm

  • Model world as objects that interacts with each other

class

Templates for objects.

instance
object

Object created from class.

method

Function inside the class.

property
attribute
field

Variable inside the class.

1.2. Classes

  • Capitalized CamelCase name convention

  • Classes are templates for objects

Listing 232. Defining class. Classes should have capitalized name
class Iris:
    pass
Listing 233. Multi-word class names should use CamelCase
class IrisSetosa:
    pass

1.3. Instances

  • Instances are also known as Objects

  • Two newlines between class and code

  • snake_case names

../_images/blueprint.png

Figure 35. Intuition definition: Class is a blueprint, instances are homes made from this plan. Image source: [ImgFre19]

Listing 234. One class and one instance
class Iris:
    pass


flower = Iris()
Listing 235. One class and three instances
class Iris:
    pass


setosa = Iris()
versicolor = Iris()
virginica = Iris()
Listing 236. Three classes and four instances
class IrisSetosa:
    pass

class IrisVersicolor:
    pass

class IrisVirginica:
    pass


iris_setosa1 = IrisSetosa()
iris_setosa2 = IrisSetosa()
iris_versicolor = IrisVersicolor()
iris_virginica = IrisVirginica()

1.4. Good engineering practices

  • Never print in a class

  • One class per file - when classes are long

  • All classes in one file - when classes are short

  • You can mix classes and functions in one file

Listing 237. Classes and Objects
class IrisSetosa:
    pass

class IrisVersicolor:
    pass

class IrisVirginica:
    pass


setosa = IrisSetosa()
versicolor = IrisVersicolor()
virginica = IrisVirginica()

1.5. Assignments

1.5.1. Classes and instances

English
  1. Define class Astronaut

  2. Define class Location

  3. Create instance twardowski of a class Astronaut

  4. Create instance watney of a class Astronaut

  5. Create instance jsc of a class Location

  6. Create instance ksc of a class Location

  7. Create instance jpl of a class Location

Polish
  1. Zdefiniuj klasę Astronaut

  2. Zdefiniuj klasę Location

  3. Stwórz instancję twardowski klasy Astronaut

  4. Stwórz instancję watney klasy Astronaut

  5. Stwórz instancję jsc klasy Location

  6. Stwórz instancję ksc klasy Location

  7. Stwórz instancję jpl klasy Location

The whys and wherefores