Home > front end >  Passing variables from classes to main class
Passing variables from classes to main class

Time:04-12

I am trying to pass the data_lst up to Class:'Paper''s function: 'save' such that I can print it from there. The structure is fixed and I am not allowed to used global variables. How do i get around this?

class Paper:
    def __init__(self):
        pass

    def add_page(self, **kwargs):
        self.p = 1
        self.pp = 5

        page = Page(self.p, self.pp, paper=self)
        return page

    def save(self, **kwargs):
        #This is where i want to print the data from get_data
        print('final price =', data_lst)

class Page:
    def __init__(self, p, pp, paper=False):
        self.paper = paper
        self.p = p
        self.pp = pp
        assert paper

    def add_fig(self):
        fig = Figure(p=self.p, pp=self.pp)
        return fig


class Figure:
    def __init__(self, p=0, pp=0):
        self.p = p
        self.pp = pp

        data_lst = self.get_data()

    def get_data(self):
        ### get some data in a list
        data_lst = [self.p for x in range(self.pp)]
        return data_lst


paper = Paper()
page1 = paper.add_page()
page1.add_fig()

#paper.save() this call needs to print the data

CodePudding user response:

You should use paper.save(data_lst=...) or change save signature to allow data_lst as a positional argument def save(self, data_lst, **kwargs):

CodePudding user response:

I modified your code a little. This is just a proposal.

I changed the fact that the page is returned when calling the add_page method. Instead I store it in the Paper object. Same for the figure.

class Paper:
    def __init__(self):
        self.page = None

    def add_page(self):
        p = 1
        pp = 5

        self.page = Page(p, pp, paper=self)

    def save(self):
        #This is where i want to print the data from get_data
        print(f"final price ={the_paper.page.fig.data_lst}")

class Page:
    def __init__(self, p, pp, paper):
        self.paper = paper
        self.p = p
        self.pp = pp
        self.fig = None

    def add_fig(self):
        self.fig = Figure(p=self.p, pp=self.pp)


class Figure:
    def __init__(self, p=0, pp=0):
        self.p = p
        self.pp = pp

        self.data_lst = self.get_data()

    def get_data(self):
        ### get some data in a list
        data_lst = [self.p for x in range(self.pp)]
        return data_lst


the_paper = Paper()
the_paper.add_page()
the_paper.page.add_fig()
the_paper.save()

NB: I removed assert for paper, since assert is not necessarily executed in production context. If you consider that paper is mandatory, then it is better to have remove its default value.

  • Related