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)

 如果访问了就会报错:

原文地址:https://www.cnblogs.com/waited/p/5256426.html