如何访问类中函数内的变量

如何访问类中函数内的变量

本文介绍了在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()

推荐答案


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.


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中,如何访问类中函数内的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 13:03