首页 > 编程语言 > 详细

Python内置函数(60)——classmethod

时间:2016-11-16 14:51:03      阅读:322      评论:0      收藏:0      [点我收藏+]

英文文档:

staticmethod(function)

Return a static method for function.

A static method does not receive an implicit first argument.

The @staticmethod form is a function decorator – see the description of function definitions in Function definitions for details.

It can be called either on the class (such as C.f()) or on an instance (such as C().f()). The instance is ignored except for its class.

 

说明:

  1. 函数功能时将一个函数,变成类的一个静态方法。

>>> class Student(object):
    def __init__(self,name):
        self.name = name
    def sayHello(lang):
        print(lang)
        if lang == en:
            print(Welcome!)
        else:
            print(你好!)
    staticmethod(sayHello)

    
>>> Student.sayHello
<function Student.sayHello at 0x02AC7810>
>>> a = Student(Bob)
>>> a.sayHello
<bound method Student.sayHello of <__main__.Student object at 0x02AD03F0>>

  2. 静态方法即可以被类调用,也可以被类的实例对象调用。

>>> Student.sayHello(en) # 类调用的时候,将‘en‘传给了lang参数
en
Welcome!

>>> a.sayHello() # 类实例对象调用的时候,将对象本身传给了lang参数
<__main__.Student object at 0x02AD03F0>
你好!

  3. 将一个方法定义成类的静态方法,正确的方法是使用 @staticmethod装饰器,这样在实例对象调用的时候,不会把实例对象本身传入静态方法的第一个参数了。

# 使用装饰器定义静态方法
>>> class Student(object):
    def __init__(self,name):
        self.name = name
    @staticmethod
    def sayHello(lang):
        print(lang)
        if lang == en:
            print(Welcome!)
        else:
            print(你好!)

            
>>> Student.sayHello(en) #类调用,‘en‘传给了lang参数
en
Welcome!

>>> b = Student(Kim) #类实例对象调用,不再将类实例对象传入静态方法
>>> b.sayHello()
Traceback (most recent call last):
  File "<pyshell#71>", line 1, in <module>
    b.sayHello()
TypeError: sayHello() missing 1 required positional argument: lang

>>> b.sayHello(zh)  #类实例对象调用,‘zh‘传给了lang参数
zh
你好!

 

Python内置函数(60)——classmethod

原文:http://www.cnblogs.com/sesshoumaru/p/6069152.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!