Search code examples
python-3.xpython-dataclassesdata-class

Python @dataclass Inheritance of Public Variables without double initialization


Want to write to variables in one class, then inherit those set variable values in another class without having set the values again.

Below code should print 100, without having to initialize the values again for subclass instance; want to use the originally set values in master class (data handler).

One class manages all income data; Data Handler, then the other classes simple inherit those values. What is the way of handling this flow structure ? Please and Thank you!!

from dataclasses import dataclass


@dataclass
class Datahandler: 


    A : int
    B : int
    C : int
    D : int
    E : int
    F : int     



Datahandler=Datahandler(100,100,50,40,10,1000)    




class Some_Class(Datahandler):       

    pass


print(Some_Class.A)

Solution

  • To define an attribute of a class, assign to it in the class definition, not inside any function.

    class Datahandler: 
        staticmember = 200
    

    The dataclass class won't help you with that. It is for defining attributes of class instances, not classes.

    You can then access the base class member in a derived class, which is what you want to do.

    class Some_Class(Datahandler):       
        pass
    
    print(Some_Class.staticmember)
    

    Also, you should avoid using the same name for a class and an instance of that class.

    Datahandler=Datahandler(100,100,50,40,10,1000) #Likely problematic

    Edit: While I answered the question as posted, there are simpler ways to do the same thing without using inheritance, as @juanpa.arrivillaga suggested.