在Python中,如何访问类中函数内的变量? [英] In Python, How Do I Access A Variable Inside A Function Of A Class?

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

问题描述

如何从课外打印num的值?



class机器人:

def add(self):

num = 10

a = 56

a = num + a

打印一个



obj1 = Robot()

obj1.add()

How to print the value of num from outside the class?

class Robot:
def add(self):
num = 10
a = 56
a = num + a
print a

obj1 = Robot()
obj1.add()

推荐答案

这是局部变量;你完全不能访问它,不仅是来自课外,甚至不是同一个课程。此外,它甚至没有任何意义:在调用期间,变量在调用堆栈上创建,整个堆栈帧从堆栈中移除(弹出)。从逻辑上讲,在运行期间,变量在调用之前不存在,并且在每次调用后都会存在。



请注意,理解堆栈是其中一个基础知识。编程资格,你不能不知道。不幸的是,在这个时刻,你没有掌握编程的整个想法,所以你必须从一开始就走在路上。不用太担心,我们都在某个时间在那里。



-SA
This is the the local variable; you cannot access it at all, not only from outside the class, but not even in the same class. Moreover, it does not even make any sense: during the call, the variable is created on the call stack, and the whole stack frame is removed from stack (popped). Logically speaking, during runtime, the variables don't exist before the call and seize to exist after each call.

Note that understanding stack is one of the very basics of programming qualification which you cannot afford to not know. Unfortunately, at this moment, you did not grasp the whole idea of programming, so you have to walk the way nearly from the very beginning. Not too worry, we all were there at some time.

—SA


这里你的解决方案,,,

Here your solution,,,
class Robot:
    num = 0
    def add(self):
        self.num = 10
        a = 56
        a = self.num + a
        print a
obj1 = Robot()
obj1.add()
print obj1.num







将'num'声明为类变量,现在可以使用类Robot的对象从类外部访问num的值。




Declare 'num' as class variable, now you can access value of num from outside of class using object of class Robot.


Hello Friend,

请看下面的代码:



Hello Friend,
Look at the code below:

class Robot:
	def __init__(self,Num):
		self.Num = Num
	def func(self):
		return self.Num





我已经定义了一个类和一个构造函数。这里'self'表示指向该类本身的指针。所以我分配了我想要操作的值。



请注意:这里Num不是类变量,它是一个实例变量,所以你想要的方式不可能发生。



但是使用'self'我可以访问函数中的变量。

我同意上述两位先生,他们绝对正确。



完成上述事情后,请输入:



I have defined a class and a constructor. Here 'self' means a pointer to that class itself. So i a assigned the value which i wanted to manipulate.

Please note : Here Num is not a class variable it is an instance variable, so the way you want cant happen.

However using 'self' i can access the variable in the function.
I agree to both the above gentlemen, they are absolutely correct.

after doing the above things, type:

r = Robot(20)



现在:


Now:

r.func()





所以你会得到输出: 20



您需要从中学到的是:类变量和实例变量之间的区别。我希望我们的讨论能让你清楚。



谢谢



So you will get the output : 20

What you need to learn from this is: the difference between a class variable and an instance variable. I hope it is clear to you from our discussion.

Thanks


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

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