1

As far as my understanding goes, Python does not really have constants, they are all attributes or variables that by convention are typed uppercase. If this is wrong, please correct me.

I'm in the situation of creating several classes that inherit from an abstract class. There are two kinds of attributes I'm concerned with

  • KIND_1 is equal to the same constant for all the children
  • KIND_2 changes children by children

My current implementation is the following

from dataclasses import dataclass, field
from abc import ABC, abstractmethod

class Parent(ABC):
  KIND_1 : int = 7

  @classmethod
  @property
  @abstractmethod
  def KIND_2(cls):
    raise NotImplementedError

@dataclass
class Child_1(Parent):
  real_attr_1 : int = 1
  real_attr_2 : int = 2
  KIND_2 : int = field(default=0, init=False, repr=False)

@dataclass
class Child_1(Parent):
  real_attr_3 : int = 100
  KIND_2 : int = field(default=17, init=False, repr=False)

After I have created a class I can access and change the "constant" attribute, but I guess I can't do much with that.

What I'm puzzled about is: why does it work? Specifically

  1. Why does @dataclass not initialize nor print KIND_1. Isn't that also an attribute of each child? I had to use field in order not to initialize KIND_2 and not to print it.
  2. What should I do in order for @dataclass to initialize some attributes defined in Parent? Looking at this answer https://stackoverflow.com/a/53085935/3410940 about how you can not have positional attributes if the parent had defaults I thought that the attributes were going to end up in __init__.
  3. I was following https://stackoverflow.com/a/53417582/3410940 when imposing to the children classes to define the constant. However, I am asking myself: what is the point of staking @classmethod and @property?
ThePunisher
  • 206
  • 1
  • 7

0 Answers0