首頁  >  文章  >  後端開發  >  python類別方法與物件方法介紹

python類別方法與物件方法介紹

高洛峰
高洛峰原創
2017-03-07 15:46:421357瀏覽

這篇文章主要和大家一起學習python類別方法與物件方法,從一個簡單例子出發進行學習,有興趣的小夥伴們可以參考一下

本文實例針對python的類別方法與對象方法進行學習研究,具體內容如下

class Test_Demo:
  TEST = 'test_value'

  def __init__(self,name,age):
    self.name = name
    self.age = age
  #static method
  @staticmethod
  def test_static():
    return Test_Demo.TEST
  #特性
  @property
  def test_property(self):
    return self.name+':'+str(self.age)
  #类方法
  @classmethod
  def test_class(self):
    return self.TEST

if __name__ == '__main__':
  test_demo = Test_Demo('zj',23)
  #print(test_demo.name)
  print(Test_Demo.test_static())
  print(test_demo.test_property)
  print(test_demo.test_class())

輸出結果:

python類別方法與物件方法介紹

註:與php不同的是:

 類別方法和靜態方法可以存取類別的靜態變數(類別變數,TEST),但都不能存取實例變數(即name,age)

 如果訪問了就會報錯:

python類別方法與物件方法介紹

以上就是本文的全部內容嗎,希望對大家的學習有幫助。

更多python類別方法與物件方法介紹相關文章請關注PHP中文網站!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn