Accessing a variable inside the method of a class

前端 未结 2 1560
面向向阳花
面向向阳花 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条回答
  •  梦毁少年i
    2021-01-21 19:27

    You could simply create a variable inside the __init__() method which gets called as soon as a class is initialized, and then you can change the value of the variable which would get reflected outside the class as well.

    It seems that you were trying to create a method save() for the class so I did the same for you, If you don't want your save() method to take any arguments then you can also use def save(self):

    class Expense:
        def __init__(self):
            #Do some initializations here
            self.TotalAmount = 0
        def save(self, amount):
            self.TotalAmount = amount
    
    
    exp = Expense()
    print exp.TotalAmount
    >>> 0
    exp.save(10)
    print exp.TotalAmount
    >>> 10
    

提交回复
热议问题