Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (18.4k points)

I have a class with a set of some generic variables in the init method, which are not specific to the class. I want to take another class that holds these variables and then have the first-class inheritance those variables.

The second class is not the parent class. It is more like a module class.

How I write this in python?

Thanks.

Class A():

   def __init__(self):

       self.generic_variable1 = 'blah'

       self.generic_variable2 = 'blah'

       self.generic_variable3 = 'blah'

       self.generic_variable4 = 'blah'

       self.generic_variable5 = 'blah'

       self.generic_variable6 = 'blah'

   

   def generic_method1(self):

       return 'blah'

   

   def class_specific_method1(self):

       pass

After creating two classes:

Class A():

   def __init__(self):

       pass

   def class_specific_method1(self):

       pass

Class B():

   def __init__(self):

       self.generic_variable1 = 'blah'

       self.generic_variable2 = 'blah'

       self.generic_variable3 = 'blah'

       self.generic_variable4 = 'blah'

       self.generic_variable5 = 'blah'

       self.generic_variable6 = 'blah'

   

   def generic_method1(self):

       return 'blah'

1 Answer

0 votes
by (36.8k points)
edited by

I think, it is a module-level dictionary, which the class can access.

d = {'k':'v','q':'r','m':'n',...}

class F:

    variables = d

    def __init__(self,...)

Or, maybe a collections.namedtuple instead of a dictionary to give you a dot access - instance.variables.attr instead of instance.variables[attr]` .

If you want individual attributes:

d = {'k':'v','q':'r','m':'n'}

class F:

    def __init__(self):

        for attr,val in d.items():

            setattr(self,attr,val)

Or set the attributes outside of the class

d = {'k':'v','q':'r','m':'n'}

class F:

    def __init__(self):

        pass

for k,v in d.items():

    setattr(F,k,v)

Learn Data Science with Python Course to improve your technical knowledge.

Related questions

0 votes
1 answer
0 votes
1 answer
asked May 31, 2020 in Data Science by blackindya (18.4k points)

Browse Categories

...