Python 实例方法、@staticmethod和@classmethod

本文详细介绍了Python中的三种方法类型:实例方法、类方法和静态方法。包括它们的定义方式及调用方法,并通过示例代码展示了如何使用这些方法。

Python 除了拥有实例方法外,还拥有静态方法和类方法。

[python]  view plain  copy
  1. class Foo(object):  
  2.     def test(self)://定义了实例方法  
  3.         print("object")  
  4.     @classmethod  
  5.     def test2(clss)://定义了类方法  
  6.         print("class")  
  7.     @staticmethod  
  8.     def test3()://定义了静态方法  
  9.         print("static")  

  • 实例方法访问方式:

[python]  view plain  copy
  1. ff.test();//通过实例调用  
  2. Foo.test(ff)//直接通过类的方式调用,但是需要自己传递实例引用  

  • 类方法访问方式:

[python]  view plain  copy
  1. Foo.test2();  
如果Foo有了子类并且子类覆盖了这个类方法,最终调用会调用子类的方法并传递的是子类的类对象。

[python]  view plain  copy
  1. class Foo2(Foo):  
  2.     @classmethod  
  3.     def test2(self):  
  4.         print(self)  
  5.         print("foo2 object")  
  6. f2=Foo2()  
  7. print(f2.test2())  

输出结果:

[python]  view plain  copy
  1. <class '__main__.Foo2'>  
  2. foo2 object  

  • 静态方法调用方式:

 静态方法就跟普通的Java静态方式一样

[python]  view plain  copy
  1. ff=Foo();
  2. ff.test3();//使用实例调用
  3. Foo.test3();//直接静态方式调用
 

转载于:https://www.cnblogs.com/lv-xing-de-mu-ne/p/7787486.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值