Accessing a variable inside the method of a class

一笑奈何 提交于 2019-12-02 04:16:55

问题


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 = blah

So I need to access TotalAmount outside of the class but I'm not sure how I would go about this.


回答1:


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



回答2:


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).



来源:https://stackoverflow.com/questions/30479081/accessing-a-variable-inside-the-method-of-a-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!