Home > database >  Python class methods to construct child classes
Python class methods to construct child classes

Time:01-04

I don't know how to cleanly reuse the classmethod of a derived class in python to construct the child class:

class Base:
     def __init__(... lots of parameters .... )
         ... assign parameters .... 
         
     @classmethod
     def from_file(cls,file)
         .... read lots of parameters ....
         return cls(.... lots of parameters .... )

class Derived(Base):
     def __init__(derived_param, .... base parameters ..... )
         super().__init__(base parameters)

     @classmethod
     def from_file(cls,file)
         ??? do i have to replicate the whole code from   
         Base.from_file() here ???? 

CodePudding user response:

You don't have to redefine a method in a child class. By default, it uses the parent function:

class Base:
     def __init__(... lots of parameters .... )
         ... assign parameters .... 
         
     @classmethod
     def from_file(cls,file)
         .... read lots of parameters ....
         return cls(.... lots of parameters .... )

class Derived(Base):
     def __init__(derived_param, .... base parameters ..... )
         super().__init__(base parameters)

derived_class = Derived(...params...)
derived_class.from_file(...params...)  # This line will work without any further changes

CodePudding user response:

Thanks. This could be the solution:

class Base:
    def __init__(self,base_var):
        self.base_var = base_var

    @classmethod
    def from_file(cls):
        """ read from file here"""
        base_init = "base_init"
        return cls(base_var=base_init)


class Derived(Base):
    def __init__(self,derived_var,base_var):
        super().__init__(base_var)
        self.derived_var = derived_var

    @classmethod
    def from_file(cls):
        derived_init = "derived_init"
        base = Base.from_file()
        derived = cls(derived_init,base.base_var)

        return derived
  •  Tags:  
  • Related