访问类中方法中的变量 [英] Accessing a variable inside the method of a class

查看:183
本文介绍了访问类中方法中的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Tkinter / Python创建一个预算程序。这是我的代码的基础:

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

所以我需要访问 TotalAmount 以外的类,但我不知道我该怎么走这个。

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

推荐答案

您可以在 __ init __()方法中创建一个变量,只要初始化一个类,就可以调用该变量,然后可以更改变量的值

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.

似乎你试图创建一个方法 save()类,所以我做了同样的,如果你不想让你的 save()方法接受任何参数,那么你也可以使用 def save (self):

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

这篇关于访问类中方法中的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆