2017年3月16日 星期四

class 下的 global ,self 筆記


x=999
class C:
  x= 6666
  def function(self):
      print x
      print self.x
  def define(self):
      print self.x
  def correct(self):
      self.x= 899
      print self.x
  def react():
      x= 89
      print x
c=C()

  • c=C() :把c實體化
  • class下的x=6666 為class專屬的變數,如果在函數內要print,使用 或改變就要使用self.x  否則只寫 print x 會跑出外部的x =999
  • print (c.x) 結果為 6666 因為class C 下的 x 是6666 。 之後若運行到c.correct() 因為已改變self.x 所以若再print (c.x) 則為899
  • def react()下的 x=89 為該函數內自定義的變數,不會改變到外面 也不會受外面影響。

x=999
class C:
  global x
  x= 6666
  def function(self):
      print x
      print self.x
  def define(self):
      print self.x
  def correct(self):
      self.x= 899
      print self.x
c=C()

  • 如果在class加上global x 且賦予該變數為6666 是說改變了x=999 為6666 並不是在class 內定義變數 ,所以使用self.x會報錯(因為class內沒有定義專屬的變數)
  • print (c.x) 結果會報錯 , 因為尚未定義class C的變數,之後若運行到c.correct() 因為設定了self.x 所以若再print (c.x) 則為899






這封郵件來自 Evernote。Evernote 是您專屬的工作空間,免費下載 Evernote

0 意見:

張貼留言

Contact

Get in touch with me


Adress/Street

12 Street West Victoria 1234 Australia

Phone number

+(12) 3456 789

Website

www.johnsmith.com