如何从课外打印num的值?
class Robot:
def add(self):
num = 10
a = 56
a = num + a
print a
obj1 = Robot()
obj1.add()
答案 0 :(得分:1)
只需将值设置为self.num
,而不只是num
:
class Robot:
def add(self):
self.num = 10
a = 56
a = self.num + a
print a
obj1 = Robot()
obj1.add()
print obj1.num #10
答案 1 :(得分:0)
您还可以将num定义为类函数中的全局变量,然后使用num:
调用它class Robot:
def add(self):
global num
num = 10
a = 56
a = num + a
print a
obj1 = Robot()
obj1.add()
print num