0

In the example provided by Martijn Pieters in What are data classes and how are they different from common classes?, he defines some class members in the class header, as well as in __init__():

class InventoryItem:
    '''Class for keeping track of an item in inventory.'''
    name: str
    unit_price: float
    quantity_on_hand: int = 0

    def __init__(
            self, 
            name: str, 
            unit_price: float,
            quantity_on_hand: int = 0
        ) -> None:
        self.name = name
        self.unit_price = unit_price
        self.quantity_on_hand = quantity_on_hand
...

What is the reason to do that, is it not enough to define them in __init__()?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Elad Weiss
  • 3,662
  • 3
  • 22
  • 50

1 Answers1

4

It is explained in this comment by Martijn Pieters♦:

there are no class attributes, there are only type annotations. See PEP 526, specifically the Class and instance variable annotations section.

ndclt
  • 2,590
  • 2
  • 12
  • 26
  • 1
    You can link to a comment, but quoting is always the right approach over posting a link, regardless. Don't forget to attribute the quote properly. – Mad Physicist Feb 20 '21 at 21:08
  • I didn't know for the link. :-) I forgot about quoting and edit my answer. Thanks. – ndclt Feb 20 '21 at 21:12
  • 1
    Keep in mind the same is true for dataclasses; the only difference is that the `dataclass` decorator uses the annotations to generate an `__init__` that does the same thing: initialize instance attributes from arguments. – chepner Feb 20 '21 at 21:15