python中的变量定义是很灵活的,很容易搞混淆,特别是对于class的变量的定义,如何定义使用类里的变量是我们维护代码和保证代码稳定性的关键。globalvariable1globalvariableclassMyClass():classvar1classval1defineclassvariableheredefinit(self,param):self。objectvar1paramdefineobjectvariablehereself。objectvar2objectval2defineobjectvariablehereself。objectfunc3()defobjectfunc1(self,param):localvar1paramdefinelcoalvariableherelocalvar2localval2definelocalvariablehereself。internalvar1internalval1defineinternalvariablehereprint(localvar1)wecanuselocalvariableofcurrenthereprint(localvar2)wecanuselocalvariableofcurrenthereprint(MyClass。classvar1)wecanuseclassvariablehere,butyouhaveusingclassnameassprefixprint(self。classvar1)wecanuseclassvariableasobjectvariablehereprint(self。objectvar1)wecanuseobjectvariablehereprint(self。objectvar2)wecanuseobjectvariablehereprint(self。internalvar1)wecanuseinternalvariablehereprint(localvar3)wecantuselocalvariableinanotherfunctionprint(globalvariable1)wecanuseglobalvariableheredefobjectfunc2(self,paramfuncval1):localvar3paramdefinelocalvariablehereprint(localvar3)wecanuselcoalvariablehereprint(self。internalvar1)wecanuseinternalvariabledefinedinclassfunc1,butyouhavetocallclassfunc1firstprint(MyClass。classvar1)wecanuseclassvariablehere,butyouhaveusingclassnameassprefixprint(self。classvar1)wecanclassvariablehereprint(self。objectvar1)wecanuseobjectvariablehereprint(self。objectvar2)wecanuseobjectvariablehereprint(globalvariable1)wecanuseglobalvariableheredefobjectfunc3(self,paramfuncval1):self。objectvar3parambecausethisfunctioncalledinconstructionfunction,sothisisdefinedasobjectvariable,notinternalvariableself。objectvar4objectval4becausethisfunctioncalledinconstructionfunction,sothisisdefinedasobjectvariable,notinternalvariableprint(globalvariable1)wecanuseglobalvariableheredefineclassfunctiondefclassfunc4():print(MyClass。classvar1)print(globalvariable1)wecanuseglobalvariablehereifnamemain:myObjectMyClass(objectval1)print(MyClass。classvar1)wecanuseclassvariabledirectlyhereprint(MyClass。objectvar1)wecantuseobjectvariablehereprint(myObject。objectvar1)wecanuseobjectvariablehereprint(myObject。objectvar2)wecanuseobjectvariablehereprint(myObject。objectvar3)wecanuseobjectvariablehereprint(myObject。objectvar4)wecanuseobjectvariablehereprint(myObject。internalvar1)wecantuseinternalvariableasobjectvariablehereMyClass。classfunc4()wecanuseclassfunctionhereMyClass。objectfunc2(myObject,localvar3)internalvariablecantbeusedinthisfunctionmyObject。objectfunc1(localvar1)callfirstfunctionmyObject。objectfunc2(localvar3)callsecondfunctionprint(globalvariable1)wecanuseglobalvariablehere 枚举了各种情况,没有办法全部枚举,但大部分情况应该都已经包含了。 1。类变量:能够通过类名或者object的self来访问到,在类的内部和外部均可达,比如classvar1 2。对象变量:可以通过对象的self来使用的变量,通过constructor一路走向去的的self初次被赋值的变量都会成为对象变量,比如objectvar1,objectvar2,objectvar3,objectvar4 3。内部变量:可以在函数中定义,并加上self前缀,在初次调用过定义的函数后,就可以在后面的对象的函数中被使用,比如internalvar1 4。局部变量:在函数内部定义,并使用的变量,在使用完之后就会被回收对类及object不可见 5。全局变量:定义在类或者函数外部,作用域在变量被定义之后的任意代码段,比如:globalvar1