Accessing a variable inside the method of a class

前端 未结 2 1559
面向向阳花
面向向阳花 2021-01-21 19:03

I\'m creating a budgeting program using Tkinter/Python. This is the basics of my code:

class Expense:
  def __init__(self):
    def Save(self)
       TotalAmount         


        
2条回答
  •  走了就别回头了
    2021-01-21 19:32

    You need to either add the variable as a property on the object (self.TotalAmount = blah) or make it a global variable:

    class Expense:
      def __init__(self):
        def Save(self)
           global TotalAmount
           TotalAmount = blah
    

    The first solution is the preferred one because having a lot of global variables will make your code hard to read. You should strive for encapsulation because it makes it easier to maintain the code in the future (changing one part of the code is less likely to break other parts).

提交回复
热议问题