类的三种方法

时间:2022-07-28 15:44:18

对于实例方法,在类里每次定义实例方法的时候都需要指定实例(该方法的第一个参数,名字约定成俗为self)。这是因为实例方法的调用离不开实例,我们必须给函数传递一个实例。假设对象a具有实例方法 foo(self, *args, **kwargs),那么调用的时候可以用 a.foo(*args, **kwargs),或者 A.foo(a, *args, **kwargs),在解释器看来它们是完全一样的。

类方法每次定义的时候需要指定类(该方法的第一个参数,名字约定成俗为cls),调用时和实例方法类似需要指定一个类。

静态方法其实和普通的方法一样,只不过在调用的时候需要使用类或者实例。之所以需要静态方法,是因为有时候需要将一组逻辑上相关的函数放在一个类里面,便于组织代码结构。一般如果一个方法不需要用到self,那么它就适合用作静态方法。

def foo(x):
print "executing foo(%s)"%(x)


class A(object):
def foo(self):
print "executing foo(%s)" % self

@classmethod
def class_foo(cls):
print "executing class_foo(%s)" % cls

@staticmethod
def static_foo():
print "executing static_foo()"

a = A()
print a.foo
print A.foo

print a.class_foo
print A.class_foo

print A.static_foo
print a.static_foo
print foo

# <bound method A.foo of <__main__.A object at 0x10d5f90d0>>
# <unbound method A.foo>
# <bound method type.class_foo of <class '__main__.A'>>
# <bound method type.class_foo of <class '__main__.A'>>
# <function static_foo at 0x10d5f32a8>
# <function static_foo at 0x10d5f32a8>
# <function foo at 0x10d5f1ed8>