'How to properly derive classes with static attributes

I have a class GFN representing Galois field numbers. The class has static attributes that are common for all the numbers within certain Galois field, e.g. the field generator polynomial. While it might be not the best possible design for the task, it serves the purpose well for a single concrete Galois field.

Now, if I want to create another class for another Galois field, I cannot just derive GFN, since the static attributes are being accessed via the class name, e.g.

 @staticmethod
def list_mapping():
    for i in range(1, GFN.size - 1):
        print(str(i) + " --> alpha^" + str(GFN.g2p[i]));

I can surely copy-paste the class, or put the Galois field parameters somewhere else, but it is not "nice". Is it possible to change the code so that it is possible to derive the class, e.g. replacing GFN with a generic reference to the class type? If not, are there other elegant metaprogramming techniques that would allow creating such classes from a template?



Solution 1:[1]

You should use a classmethod like so:

@classmethod
def list_mapping(cls):
    for i in range(1, cls.size - 1):
        print(str(i) + " --> alpha^" + str(cls.g2p[i]));

Subclasses will then be able to override the size and g2p attributes.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Bharel