How to pass variable between class functions?

Asked

Viewed 92 times

0

I need to pass the variable price for the function whatever of Tela4. I am new to both programming and the language itself and I have serious problems with this solution despite imagining that it is very simple.

The code is currently like this (cost_output refers to a label kivy):

class Tela2(Screen):
    def op_dimoff(self):
        self.price = float((int(self.ngd) * 0.87 * 1.75) + self.price_inv)

class Tela4 (Screen):
    def whatever(self):
        tela_two = Tela2
        self.cost_output.text = str(tela_two.price)
  • Is there a problem? Your code does not seem to be complete.

  • @I ask the first question I ask here so I thought it might not be a good idea to put the whole code so it doesn’t get this big. In short, implementing so above I get an error AttributeError: 'Tela2' object has no attribute 'price'

  • Whole is not good, but relevant parts are. In this case it seems that neither has the field

  • Did the answer solve your question? Do you think you can accept it? See [tour] if you don’t know how you do it. This would help a lot to indicate that the solution was useful for you. You can also vote on any question or answer you find useful on the entire site (when you have 15 points).

1 answer

1

Variables are language tricks and they exist in code, so you don’t pass them, you pass the values that the variables support. In this case it seems that neither wants to pass anything, only wants to access the state of an existing variable in another class.

Variables need to exist, so it would have to be something like this:

class Tela2(Screen):
    price = 0.0
    def op_dimoff(self):
        self.price = float((int(self.ngd) * 0.87 * 1.75) + self.price_inv)

I put in the Github for future reference.

Note that the variable price there belongs to the class and not the method (what you called a function, but which has that name when it is within a class), it is important to make this distinction, if you still do not understand this you need to learn before proceeding.

But I want to make some considerations:

  • if this is more than I exercise it is not correct to use this type of data for monetary value.

  • To be able to program you need to understand what you’re doing, that is, you need to build the knowledge to do advanced things, and apparently you’re struggling with something basic in an advanced problem. I would review the way you learn just by going to the advanced when you master the basics, it’s much more productive.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.