houbin 发表于 2017-5-4 10:43:07

python类变量作用域用法小结

函数内部局部变量,此时aint为局部变量
class Test:
    def __init__(self):
      aint = 6
      print aint
#print self.aint报错
test = Test()
print test.aint

结果
6
报错
==================================
函数内声明类的属性


class Test:
    def __init__(self):
      self.aint = 6
      print self.aint

test = Test()
print test.aint

结果
6
6
=========================================
函数外声明的是类的属性
class Test:
    aint = 3
    def __init__(self):
      print self.aint

test = Test()
print test.aint

结果
3
3
页: [1]
查看完整版本: python类变量作用域用法小结