python中staticmethod classmethod及普通函数的区别

本文详细解释了Python中三种方法的区别:静态方法、类方法及普通方法。通过具体示例介绍了它们如何被定义和调用,以及每种方法的使用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

http://genggeng.iteye.com/blog/1290458

staticmethod 基本上和一个全局函数差不多,只不过可以通过类或类的实例对象(python里光说对象总是容易产生混淆, 因为什么都是对象,包括类,而实际上类实例对象才是对应静态语言中所谓对象的东西)来调用而已, 不会隐式地传入任何参数。这个和静态语言中的静态方法比较像。


classmethod 是和一个class相关的方法,可以通过类或类实例调用,并将该class对象(不是class的实例对象)隐式地 当作第一个参数传入。就这种方法可能会比较奇怪一点,不过只要你搞清楚了python里class也是个真实地 存在于内存中的对象,而不是静态语言中只存在于编译期间的类型。


正常的方法就是和一个类的实例对象相关的方法,通过类实例对象进行调用,并将该实例对象隐式地作为第一 个参数传入,这个也和其它语言比较像。


可如下示例:


Python代码  收藏代码
  1. #!/usr/bin/python  
  2. #coding:utf-8  
  3.   
  4. #author:    gavingeng  
  5. #date:      2011-12-03 10:50:01   
  6.   
  7. class Person:  
  8.   
  9.     def __init__(self):  
  10.         print "init"  
  11.  
  12.     @staticmethod  
  13.     def sayHello(hello):  
  14.         if not hello:  
  15.             hello='hello'  
  16.         print "i will sya %s" %hello  
  17.  
  18.  
  19.     @classmethod  
  20.     def introduce(clazz,hello):  
  21.         clazz.sayHello(hello)  
  22.         print "from introduce method"  
  23.   
  24.     def hello(self,hello):  
  25.         self.sayHello(hello)  
  26.         print "from hello method"         
  27.   
  28.   
  29. def main():  
  30.     Person.sayHello("haha")  
  31.     Person.introduce("hello world!")  
  32.     #Person.hello("self.hello") #TypeError: unbound method hello() must be called with Person instance as first argument (got str instance instead)  
  33.       
  34.     print "*" * 20  
  35.     p = Person()  
  36.     p.sayHello("haha")  
  37.     p.introduce("hello world!")  
  38.     p.hello("self.hello")  
  39.   
  40. if __name__=='__main__':  
  41.     main()  


output:


Shell代码  收藏代码
  1. i will sya haha  
  2. i will sya hello world!  
  3. from introduce method  
  4. ********************  
  5. init  
  6. i will sya haha  
  7. i will sya hello world!  
  8. from introduce method  
  9. i will sya self.hello  
  10. from hello method  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值