A More Productive Way to write Python Classes

A More Productive Way to write Python Classes

If you're an Object Oriented programmer like me, you write a bunch of classes often.

To increase your productivity, Python has abstracted most of its boilerplate code. Let's see how we can use them in our code.

Here's a trivial example of...

A typical Python Class

class CreditCard:
    def __init__(self, owner: str, bank: str):
        self.owner = owner
        self.bank = bank
        self.item_cost = item_cost
        self.balance = 100

    def purchase_item(self, item_cost: int) -> str:
        if self.balance > item_cost:
            # do some cash transfer here
            self.balance -= item_cost
            return "successful transaction"

    def __repr__(self):
        return f'Brand new {self.__class__.__name__}'

Cool right? But here's...

A cooler way to write Python classes

from dataclasses import dataclass

@dataclass
class CreditCard:
    owner: str
    bank: str
    item_cost: int
    balance: int = 100

    def purchase_item(self, item_cost: int) -> str:
        if self.balance > item_cost:
            # do some cash transfer here
            self.balance -= item_cost
            return "successful transaction"

Did you notice we didn't have to write the __init__() and __repr__() dunder methods? Well, from Python 3.7 you can decorate your classes with the @dataclass decorator.

This abstracts a bunch of boilerplate code we write daily including:

  • __init__
  • __repr__
  • __eq__
  • and others.

You can read more about it here.

Let me know how this features would help you cut your dev-time and increase your productivity in the comment's section.