10.4. Methods

10.4.1. About

  • Methods are functions in the class

  • First argument is always instance (self)

  • While calling function you never pass self

  • Prevents copy-paste code

  • Improves readability

  • Improves refactoring

  • Decomposes bigger problem into smaller chunks

method

Function inside the class which takes self as a first argument.

10.4.2. Rationale

point_x = 1
point_y = 2
point_z = 3

print(point_x)
print(point_y)
print(point_z)
class Point:
    def __init__(self, x, y, z):
        self.x = x
        self.y = y
        self.z = z

    def get_coordinates(self):
        return self.x, self.y, self.z

    def to_string(self):
        print(f'Point(x={self.x}, y={self.y}, z={self.z})')


point = Point(x=1, y=2, z=3)

print(point.x)      # 1
print(point.y)      # 2
print(point.z)      # 3

point.to_string()
# Point(x=1, y=2, z=3)

p = point.get_coordinates()
print(p)
# (1, 2, 3)

10.4.3. Methods without arguments

Listing 239. Methods without arguments
class Astronaut:
    def say_hello(self):
        print('My name... Jose Jimenez')


astro = Astronaut()
astro.say_hello()
# My name... Jose Jimenez

10.4.4. Methods with required argument

Listing 240. Methods with required argument
class Astronaut:
    def say_hello(self, name):
        print(f'My name... {name}')


astro = Astronaut()

astro.say_hello(name='Jose Jimenez')
# My name... Jose Jimenez

astro.say_hello('Jose Jimenez')
# My name... Jose Jimenez

astro.say_hello()
# TypeError: say_hello() missing 1 required positional argument: 'name'

10.4.5. Methods with optional argument (with default value)

Listing 241. Methods with arguments with default value
class Astronaut:
    def say_hello(self, name='Unknown'):
        print(f'My name... {name}')


astro = Astronaut()

astro.say_hello(name='Jose Jimenez')
# My name... Jose Jimenez

astro.say_hello('Jose Jimenez')
# My name... Jose Jimenez

astro.say_hello()
# My name... Unknown

10.4.6. Methods Accessing Fields

Listing 242. Methods Accessing Fields
class Astronaut:
    def __init__(self, name):
        self.name = name

    def say_hello(self):
        print(f'My name... {self.name}')


astro = Astronaut('Jose Jimenez')
astro.say_hello()
# My name... Jose Jimenez

10.4.7. Methods Calling Other Methods

Listing 243. Methods Calling Other Methods
class Astronaut:
    def get_name(self):
        return 'Jose Jimenez'

    def say_hello(self):
        name = self.get_name()
        print(f'My name... {name}')


astro = Astronaut()
astro.say_hello()
# My name... Jose Jimenez
Listing 244. Methods calling other methods
class Iris:
    def __init__(self):
        self.sepal_length = 5.1
        self.sepal_width = 3.5
        self.petal_length = 1.4
        self.petal_width = 0.2

    def sepal_area(self):
        return self.sepal_length * self.sepal_width

    def petal_area(self):
        return self.petal_length * self.petal_width

    def total_area(self):
        return self.sepal_area() + self.petal_area()


flower = Iris()
print(flower.total_area())
# Total area: 18.13

10.4.8. Assignments

10.4.8.1. Methods

  • Complexity level: easy

  • Lines of code to write: 15 lines

  • Estimated time of completion: 15 min

  • Solution: solution/syntax_methods.py

English
  1. Define class Iris

  2. Define method total() which returns sum of all numerical attributes of an object

    • "Sepal length"

    • "Sepal width"

    • "Petal length"

    • "Petal width"

  3. Define method get_length() which returns number of numerical fields (use: self.__dict__)

  4. Define method mean() which calculates mean of all numerical attributes of an object

  5. Create setosa object with attributes set at the initialization (see input data)

  6. Create virginica object with attributes set at the initialization (see input data)

  7. Print species name, total and mean of each instance

Polish
  1. Zdefiniuj klasę Iris

  2. Zdefiniuj metodę total() klasy Iris zwracającą sumę wszystkich atrybutów numerycznych obiektu:

    • "Sepal length"

    • "Sepal width"

    • "Petal length"

    • "Petal width"

  3. Zdefiniuj metodę get_length() która zwraca ilość pól numerycznych (użyj: self.__dict__)

  4. Zdefiniuj metodę mean() klasy Iris wyliczającą średnią wszystkich atrybutów numerycznych obiektu

  5. Stwórz obiekt setosa z pomiarami podawanymi przy inicjalizacji (patrz dane wejściowe)

  6. Stwórz obiekt virginica z pomiarami podawanymi przy inicjalizacji (patrz dane wejściowe)

  7. Wypisz nazwę gatunku oraz sumę i średnią z pomiarów dla każdej instancji

Input
Table 12. Initial values

Sepal length

Sepal width

Petal length

Petal width

Species

5.1

3.5

1.4

0.2

setosa

5.8

2.7

5.1

1.9

virginica