16.14. OOP Methods and Methods

  • 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

16.14.1. Syntax

>>> class MyClass:
...     def __init__(self):
...         self.myfield = 'some value'
...
...     def mymethod(self):
...         return self.myfield
>>>
>>>
>>> my = MyClass()
>>> my.mymethod()
'some value'

16.14.2. Methods Accessing Fields

Methods Accessing Fields:

>>> class User:
...     def __init__(self, name):
...         self.name = name
...
...     def say_hello(self):
...         return f'My name... {self.name}'
>>>
>>>
>>> jose = User('José Jiménez')
>>> jose.say_hello()
'My name... José Jiménez'

self.name must be defined before accessing:

>>> class User:
...     def say_hello(self):
...         return f'My name... {self.name}'
>>>
>>>
>>> jose = User()
>>> jose.say_hello()
Traceback (most recent call last):
AttributeError: 'User' object has no attribute 'name'

16.14.3. Methods Calling Other Methods

Methods Calling Other Methods:

>>> class User:
...     def get_name(self):
...         return 'José Jiménez'
...
...     def say_hello(self):
...         name = self.get_name()
...         return f'My name... {name}'
>>>
>>>
>>> jose = User()
>>> jose.say_hello()
'My name... José Jiménez'

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()
>>> flower.total_area()
18.13

Since Python 3.7 there is a @dataclass decorator, which automatically generates __init__() method with arguments and set-up fields for you. More information in OOP Dataclass.

>>> from dataclasses import dataclass
>>>
>>>
>>> @dataclass
... class Iris:
...     sepal_length = 5.1
...     sepal_width = 3.5
...     petal_length = 1.4
...     petal_width = 0.2
...     species: str = 'Iris'
...
...     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()
>>> flower.total_area()
18.13

16.14.4. Examples

$ pip install atlassian-python-api
>>> 
... from atlassian import Jira
...
... jira = Jira(
...     url='https://example.com:8080',
...     username='myusername',
...     password='mypassword')
...
... JQL = 'project = DEMO AND status IN ("To Do", "In Progress") ORDER BY issuekey'
...
... result = jira.jql(JQL)
... print(result)
>>> 
... from atlassian import Confluence
...
... confluence = Confluence(
...     url='https://example.com:8090',
...     username='myusername',
...     password='mypassword')
...
... result = confluence.create_page(
...     space='DEMO',
...     title='This is the title',
...     body='This is the body. You can use <strong>HTML tags</strong>!')
...
... print(result)
>>> 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 show(self):
...         return f'Point(x={self.x}, y={self.y}, z={self.z})'
>>>
>>>
>>> point = Point(x=1, y=2, z=3)
>>>
>>> vars(point)
{'x': 1, 'y': 2, 'z': 3}
>>>
>>> point.get_coordinates()
(1, 2, 3)
>>>
>>> point.show()
'Point(x=1, y=2, z=3)'

16.14.5. Use Case - 0x01

>>> class Counter:
...     current_value: int
...
...     def __init__(self):
...         self.current_value = 0
...
...     def increment(self):
...         self.current_value += 1
...
...     def decrement(self):
...         self.current_value -= 1
...         if self.current_value < 0:
...             raise ValueError('Cannot decrement below zero')
...
...     def show(self):
...         return self.current_value
>>>
>>>
>>> c = Counter()
>>>
>>> c.increment()
>>> c.increment()
>>> c.show()
2
>>>
>>> c.decrement()
>>> c.decrement()
>>> c.show()
0
>>>
>>> c.decrement()
Traceback (most recent call last):
ValueError: Cannot decrement below zero

16.14.6. Use Case - 0x01

>>> from typing import Literal
>>>
>>>
>>> class Car:
...     brand: str
...     model: str
...     color: str
...     engine: Literal['on', 'off']
...
...     def __init__(self, brand, model, color):
...         self.brand = brand
...         self.model = model
...         self.color = color
...         self.engine = 'off'
...
...     def engine_start(self):
...         self.engine = 'on'
...
...     def engine_stop(self):
...         self.engine = 'off'
...
...     def drive_to(self, destination):
...         if self.engine == 'off':
...             raise RuntimeError('Engine is off, cannot drive')
...         else:
...             return f'Driving to {destination}'
>>>
>>>
>>> maluch = Car('Fiat', '126p', color='red')
>>>
>>> maluch.drive_to('Karpacz')
Traceback (most recent call last):
RuntimeError: Engine is off, cannot drive
>>>
>>> maluch.engine_start()
>>> maluch.drive_to('Karpacz')
'Driving to Karpacz'
>>> maluch.engine_stop()
>>>
>>> maluch.engine_start()
>>> maluch.drive_to('Poznan')
'Driving to Poznan'
>>> maluch.engine_stop()