Python

Write an awesome doc for Python. A very nice an practical one extracted from Python official documentation.

View on GitHub

Class

[!NOTE]

Different paradigms are not necessarily exclusive, in fact in OOP we use imperative programming within our methods to manipulate the data. And on the other hand you’ve already noticed that in Python we used a lot of OOP related concepts.

OOP

Let’s assume we are cooking:

Or another example of OOP would be cars:

Car state, and its methods

[!TIP]

With OOP we are not removing all that complexity, we are just hiding it behind a user friendly API which them everybody can easy use.

OOP in Python

[!NOTE]

BTW we have not forgot to talk about__init__ method. We will cover that a little further down the line. So sit tight while we are learning some new stuff.

A Short Summary of Jargons in OOP

[!NOTE]

These are oversimplified definitions of these jargons, but we have to walk you before you can run.

Types in Python are Classes

Defining a New Method

class Car:
    def __init__(self, model: str, color: str):
        self.model = model
        self.color = color
        self.start = False

    def ignite(self):
        self.start = True


mercedes = Car("Mercedes", "green")
print(f"Is your car on: {mercedes.color}")
mercedes.ignite()
print(f"After igniting your car, its start state is {
      "on" if mercedes.start is True else "off"}")

[!CAUTION]

Classes in Python are dynamic by nature. Meaning you can do something like this in your code:

mercedes.license_plate = "RAKL8136"
print(mercedes.license_plate)

But you should remember that:

  1. This attribute will be added to the mercedes object only and e.g. if you have other objects they won’t be having it.
  2. Be careful when coding, with a simple typo you might experience runtime errors. So it is a good thing that we have intellisense in our VSCode and you should use it.

Static Attributes

Static Data Attributes

class Car:
    has_engine = True

    def __init__(self):
        self.start = False

mercedes = Car()
print(mercedes.has_engine)
print(Car.has_engine)
print(mercedes.__dict__)
print(Car.__dict__)

Static Methods

import uuid


class Profile:
    """ User profile """

    @staticmethod
    def _gen_id() -> str:
        return str(uuid.uuid4())

    def __init__(self, username: str) -> None:
        self.username = username
        self.id = Profile._gen_id()

    def whoami(self) -> str:
        return "{0.id}: {0.username}".format(self)

Docstring for Classes

[!NOTE]

We have talked about docstring here, read that part if you have forgotten what it was.

class GitHubAccount:
    """
    User GitHub account profile info.

    Attributes:
      username: Username of their account
      avatar: User's GitHub avatar.
        By default our system uses it as user's avatar.
      linked_repos: A list of all linked repositories.
        This attribute is nullable.
    """

    @staticmethod
    def _get_avatar(username: str) -> str:
        """ Returns a direct link to the user's avatar. """
        # ...
        user_id = 123  # dummy value
        return f"https://avatars.githubusercontent.com/u/{user_id}?v=4&size=64"

    def __init__(self, username: str):
        self.username = username
        self.avatar = GitHubAccount._get_avatar(username)
        self.linked_repos = None

[!TIP]

You can see all the docstrings written for a class or a method by using the built-in help function:

help(User)
help(User._get_avatar)
help(User.__init__)

YouTube/Aparat