Home > OS >  To call method of Class1 in method of Class2 if instances of classes are created in main function
To call method of Class1 in method of Class2 if instances of classes are created in main function

Time:10-16

I have 2 classes:

class ClassOne:
    def __init__(self, file_name):
        self.file_name = file_name
        self.dict = {}

    def load(self):
        #reads from file and parse into dictionary self.dict
       

    @staticmethod
    def regions(self):
        return list(self.dict.keys()) #returns a list of keys of the dictionary dict

and

class ClassTwo:
    def __init__(self, file_name):
        self.file_name = file_name
        self.dict = {}

    def load(self):
        regions = ClassOne.regions(self)#The issue is here

The load() method does similar things in both classes: open file csv, read from file and parse data into dictionary dict. The only difference that method load() of ClassTwo must call method regions() of the class ClassOne Also, I have main function where I create objects (if I replace the code from main function inside and use line regions =class_one_object.regions() and remove static from method declaration, everything works fine, but following the task, I need to use this ):

def main():

    class_one_object = ClassOne("file1.csv")
    class_one_object.load ():

    class_two_object = ClassTwo("file2.csv")
    class_two_object.load ():
   

if __name__ == "__main__":
    main()

Could you help me with the issue, please? I would appreciate any help. Thanks.

CodePudding user response:

Inheritance allows you to do what you want without any copy-pasting or static methods. You create a very detailed ClassOne then inherit it in ClassTwo so that you can access load and regions from there.

Notice the use of super() that gives you a handle to ClassOne while being inside ClassTwo, which allows you to use ClassOne.load.

class ClassOne:
    def __init__(self, file_name):
        self.file_name = file_name
        self.dict = {}

    def load(self):
        print(f"Loading {self.file_name}")
        pass # Do something here.

    def regions(self):
        return list(self.dict.keys()) 


class ClassTwo(ClassOne):
    def load(self):
        super().load() # <---
        self.regions()
        

c1 = ClassOne("file1.csv")
c1.load()
# >>> Loading file1.csv

c2 = ClassTwo("file2.csv")
c2.load()
# >>> Loading file2.csv

CodePudding user response:

OK, tried to understand your question.

my inputs, file1.csv:

a,1,2,3
b,4,5,6

and file2.csv

c,7,8,9
d,10,11,12

my code :

import csv


class ClassOne:
    def __init__(self, file_name):
        self.file_name = file_name
        self.dict = {}

    def load(self):
        #reads from file and parse into dictionary self.dict
        with open(self.file_name, newline='') as csvfile:
            spamreader = csv.reader(csvfile, delimiter=',')
            for row in spamreader:
                    print(' '.join(row))
                    self.dict[row[0]] = row[1]

    @staticmethod ## works with this line commented out or not
    def regions(self):
        return list(self.dict.keys()) #returns a list of keys of the dictionary dict


class ClassTwo:
    def __init__(self, file_name):
        self.file_name = file_name
        self.dict = {}

    def load(self):
        print('****')
        #reads from file and parse into dictionary self.dict
        with open(self.file_name, newline='') as csvfile:
            spamreader = csv.reader(csvfile, delimiter=',')
            for row in spamreader:
                    print(' '.join(row))
                    self.dict[row[0]] = row[1]
        regions = ClassOne.regions(self)#The issue is here
        print('\nregions', regions)


def main():

    class_one_object = ClassOne("file1.csv")
    class_one_object.load()

    class_two_object = ClassTwo("file2.csv")
    class_two_object.load()
   

if __name__ == "__main__":
    main()

output:

a 1 2 3
b 4 5 6
****
c 7 8 9
d 10 11 12

regions ['c', 'd']

but I dont get any error, please let me know what I am doing wrong

  • Related