先看看下面代码:
class TestClass(object): val1 = 100 def __init__(self): self.val2 = 200 def fcn(self,val = 400): val3 = 300 self.val4 = val self.val5 = 500 if __name__ == '__main__': inst = TestClass() print TestClass.val1 print inst.val1 print inst.val2 print inst.val3 print inst.val4 print inst.val5
val2是成员变量,可以由类的对象来调用,这里可以看出成员变量一定是以self.的形式给出的,因为self的含义就是代表实例对象;
val3不是成员变量,它只是函数fcn内部的局部变量;
val4和val5也都不是成员变量,虽是以self.给出,但并没有在构造函数中初始化。
再看看下面的代码(#号后面的是运行结果):
inst1 = TestClass() inst2 = TestClass() print TestClass.val1 # 100 print inst1.val1 # 100 inst1.val1 = 1000 print inst1.val1 # 1000 print TestClass.val1 # 100 TestClass.val1 =2000 print inst1.val1 # 1000 print TestClass.val1 # 2000 print inst2.val1 # 2000 inst3 = TestClass() print inst3.val1 # 2000
原文地址:http://blog.csdn.net/lc_910927/article/details/38757363