Python 3 内置函数 - `staticmethod()`函数

Python 3 内置函数 - staticmethod()函数

0. staticmethod()函数

将方法转换为静态方法。

1. 使用方法:

Help on class staticmethod in module builtins:

class staticmethod(object)
 |  staticmethod(function) -> method
 |  
 |  Convert a function to be a static method.
 |  
 |  A static method does not receive an implicit first argument.
 |  To declare a static method, use this idiom:
 |       ## 使用方法:
 |       class C:
 |           @staticmethod
 |           def f(arg1, arg2, ...):
 |               ...
 |  
 |  It can be called either on the class (e.g. C.f()) or on an instance
 |  (e.g. C().f()). Both the class and the instance are ignored, and
 |  neither is passed implicitly as the first argument to the method.
 |  
 |  Static methods in Python are similar to those found in Java or C++.
 |  For a more advanced concept, see the classmethod builtin.
 |  
 |  Methods defined here:
 |  
 |  __get__(self, instance, owner, /)
 |      Return an attribute of instance, which is of type owner.
 |  
 |  __init__(self, /, *args, **kwargs)
 |      Initialize self.  See help(type(self)) for accurate signature.
 |  
 |  ----------------------------------------------------------------------
 |  Static methods defined here:
 |  
 |  __new__(*args, **kwargs) from builtins.type
 |      Create and return a new object.  See help(type) for accurate signature.
 |  
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |  
 |  __dict__
 |  
 |  __func__
 |  
 |  __isabstractmethod__

2. 使用示例

示例1.

普通调用类方法的示例。

>>> class class_a():
>>>     def say_hello(self):
>>>         print("hello.")
    
>>> a = class_a()   # 先实例化对象
>>> a.say_hello()   # 后调用函数 

# output:
hello.

示例2.

>>> class class_a:
>>>     @staticmethod
>>>     def say_hello():   # 注:staticmethod 不需要 self.
>>>         print('hello')
    
>>> class_a.say_hello()   # 直接 `Class.method()` 调用。

# output:
hello.

你可能感兴趣的:(#,Python,3,内置函数,python)