Click here to Skip to main content
15,891,033 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
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()
Posted

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
 
Share this answer
 
v2
Comments
Deepak Singh 4-Apr-15 0:21am    
Thanks a lot
Sergey Alexandrovich Kryukov 4-Apr-15 0:28am    
You are welcome. Will you accept the answer formally?
—SA
Here your solution,,,
Python
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



Declare 'num' as class variable, now you can access value of num from outside of class using object of class Robot.
 
Share this answer
 
Hello Friend,
Look at the code below:

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


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


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
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900