在Python中使用@staticmethod装饰器定义静态方法
@staticmethod是一个内置的装饰器,它在 Python 的类中定义了一个静态方法。 静态方法不接收任何引用参数,无论它是由类的实例调用还是由类本身调用。

10年积累的网站设计、成都网站建设经验,可以快速应对客户对网站的新想法和需求。提供各种问题对应的解决方案。让选择我们的客户得到更好、更有力的网络服务。我虽然不认识你,你也不认识我。但先网站制作后付款的网站建设流程,更有榕城免费网站建设让你可以放心的选择与我们合作。
@staticmethod 特性
- 在类中声明静态方法。
- 它不能有
cls或self参数。 - 静态方法无法访问类属性或实例属性。
- 静态方法可以使用
ClassName.MethodName()调用,也可以使用object.MethodName()调用。 - 它可以返回类的对象。
下面的示例演示如何在类中定义静态方法:
Example: Define Static Method
class Student:
name = 'unknown' # class attribute
def __init__(self):
self.age = 20 # instance attribute
@staticmethod
def tostring():
print('Student Class') 上面,Student类使用@staticmethod装饰器将tostring()方法声明为静态方法。 注意不能有self或cls参数。
静态方法可以使用ClassName.MethodName()或object.MethodName()调用,如下图所示。
Example: Calling Class Method using Object
>>> Student.tostring()
'Student Class'
>>> Student().tostring()
'Student Class'
>>> std = Student()
>>> std.tostring()
'Student Class' 静态方法无法访问类属性或实例属性。如果尝试这样做,将会引发错误。
Example: Static Method
class Student:
name = 'unknown' # class attribute
def __init__(self):
self.age = 20 # instance attribute
@staticmethod
def tostring():
print('name=',name,'age=',self.age) 当您调用上面的静态方法时,下面将是输出。
>>> Student.tostring()
Traceback (most recent call last):
File "", line 1, in
Student.tostring()
File "", line 7, in display
print('name=',name,'age=',self.age)
NameError: name 'name' is not defined @classmethod vs @staticmethod
下表列出了类方法与静态方法的区别:
| @classmethod | @staticmethod |
|---|---|
| 声明一个类方法。 | 声明一个静态方法。 |
| 它可以访问类属性,但不能访问实例属性。 | 它不能访问类属性或实例属性。 |
可以使用ClassName.MethodName()或object.MethodName()来调用。 |
可以使用ClassName.MethodName()或object.MethodName()来调用。 |
| 它可以用来声明返回类对象的工厂方法。 | 它可以返回类的对象。 |
本文标题:在Python中使用@staticmethod装饰器定义静态方法
转载源于:http://www.jxjierui.cn/article/djophgs.html


咨询
建站咨询
