Python 除了拥有实例方法外,还拥有静态方法和类方法。
[python]
view plain
copy
- class Foo(object):
- def test(self)://定义了实例方法
- print("object")
- @classmethod
- def test2(clss)://定义了类方法
- print("class")
- @staticmethod
- def test3()://定义了静态方法
- print("static")
- 实例方法访问方式:
[python]
view plain
copy
- ff.test();//通过实例调用
- Foo.test(ff)//直接通过类的方式调用,但是需要自己传递实例引用
- 类方法访问方式:
[python]
view plain
copy
- Foo.test2();
[python]
view plain
copy
- class Foo2(Foo):
- @classmethod
- def test2(self):
- print(self)
- print("foo2 object")
- f2=Foo2()
- print(f2.test2())
输出结果:
[python]
view plain
copy
- <class '__main__.Foo2'>
- foo2 object
- 静态方法调用方式:
静态方法就跟普通的Java静态方式一样
[python]
view plain
copy
- ff=Foo();
- ff.test3();//使用实例调用
- Foo.test3();//直接静态方式调用