python 静态方法 类方法 的作用_Python中的@staticmethod有什么意义?

这是

static methods的帖子.总结:

>实例方法:将实例作为第一个参数

>类方法:将类作为第一个参数

> static methods:不需要作为第一个参数

关于你的问题:

>是的.虽然变量名self是约定,但它与实例有关.

>静态方法可用于对同一类下的类似实用程序方法进行分组.

>对于类中的方法,您需要将self添加为第一个参数,或者使用@staticmethod修饰它的方法.没有参数的“非修饰方法”会引发错误.

通过参数调用时,可以更清楚地看到这些是如何工作的.修改过的例子:

class TestClass:

weight = 200 # class attr

def __init__(self, size):

self.size = size # instance attr

def instance_mthd(self, val):

print("Instance method, with 'self':", self.size*val)

@classmethod

def class_mthd(cls, val):

print("Class method, with `cls`:", cls.weight*val)

@staticmethod

def static_mthd(val):

print("Static method, with neither args:", val)

a = TestClass(1000)

a.instance_mthd(2)

# Instance method, with 'self': 2000

TestClass.class_mthd(2)

# Class method, with `cls`: 400

a.static_mthd(2)

# Static method, with neither args: 2

总的来说,您可以在访问方面考虑每种方法:

>如果需要访问实例或实例组件(例如实例属性),请使用实例方法,因为它将self作为第一个参数传递.

>同样,如果需要访问类,请使用类方法.

>如果既不访问实例也不访问类很重要,则可以使用静态方法.

请注意,在上面的示例中,为每种方法类型传递了相同的参数,但是对self和cls的实例和类属性的访问权限各不相同.

注意,有一种方法可以通过使用self .__ class__从实例方法访问类组件,从而避免了对类方法的需求:

...

def instance_mthd2(self, val):

print("Instance method, with class access via `self`:", self.__class__.weight*val)

...

a.instance_mthd2(2)

# Instance method, with class access via `self`: 400

REF:我建议观看Raymond Hettinger的talk Python的类开发工具包,它通过示例清楚地阐明了每种方法类型的用途.

你可能感兴趣的:(python,静态方法,类方法,的作用)