python類方法與對象方法學習


 1 class Test_Demo:
 2     TEST = 'test_value'
 3 
 4     def __init__(self,name,age):
 5         self.name = name
 6         self.age = age
 7     #static method
 8     @staticmethod
 9     def test_static():
10         return Test_Demo.TEST
11     #特性
12     @property
13     def test_property(self):
14         return self.name+':'+str(self.age)
15     #類方法
16     @classmethod
17     def test_class(self):
18         return self.TEST
19 
20 if __name__ == '__main__':
21     test_demo = Test_Demo('zj',23)
22     #print(test_demo.name)
23     print(Test_Demo.test_static())
24     print(test_demo.test_property)
25     print(test_demo.test_class())

輸出結果:

 

 

注:與php不同的是:

 類方法和靜態方法可以訪問類的靜態變量(類變量,TEST),但都不能訪問實例變量(即name,age)

 如果訪問了就會報錯:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM