Python——在類和方法的外部和內部使用變數


Python 是一種面向物件的程式語言。Python 中幾乎所有東西都是物件,有自己的屬性和方法。類就像一個物件構造器,或一個建立物件的“藍圖”。

在類之外定義的變數可以透過編寫變數名來訪問類或類中的任何方法。

示例

# defined outside the class'
# Variable defined outside the class.
outVar = 'outside_class'    
print("Outside_class1", outVar)
''' Class one '''
class Ctest:
   print("Outside_class2", outVar)
   def access_method(self):
      print("Outside_class3", outVar)
# Calling method by creating object
uac = Ctest()
uac.access_method()
''' Class two '''
class Another_ Ctest_class:
   print("Outside_class4", outVar)
   def another_access_method(self):
      print("Outside_class5", outVar)
# Calling method by creating object
uaac = Another_ Ctest_class()
uaac.another_access_method()
The variables that are defined inside the methods can be accessed within that method only by simply using the variable name.
# defined inside the method'
'''class one'''
class Ctest:
   print()
   def access_method(self):
      # Variable defined inside the method.
      inVar = 'inside_method'
      print("Inside_method3", inVar)
uac = Ctest()
uac.access_method()
'''class two'''
class AnotherCtest:
   print()
   def access_method(self):
      print()
uaac = AnotherCtest()
uaac.access_method()

更新於:06-Aug-2020

2K+ 瀏覽

開啟你的 職業生涯

透過完成教程獲得認證

開始
廣告