(转)[Python]实例方法、类方法、静态方法
原文:https://zhuanlan.zhihu.com/p/40162669
一、类(class)和实例(instance)
类是创建实例的模板,而实例则是一个一个具体的对象,各个实例拥有的数据都互相独立,互不影响。以Dog类为例,类就像一个对象工厂,可以生产一个或多个实例对象。
>>> class Dog(object):
... pass
...
>>> Dog
<class '__main__.Dog'>
>>> dog = Dog()
>>> dog
<__main__.Dog object at 0x10cd194a8>
>>> dog2 = Dog()
>>> dog2
<__main__.Dog object at 0x10cd19518>
二、初探实例方法、类方法、静态方法
先直接上代码:
class MyClass(object):
# 实例方法
def instance_method(self):
print('instance method called', self)
# 类方法
@classmethod
def class_method(cls):
print('class method called', cls)
# 静态方法
@staticmethod
def static_method():
print('static method called')
上述MyClass类中分别定义了三种不同类型的方法。
这三种方法在定义上(形式上)有如下的不同之处:
- 实例方法是一个普通的函数,类方法和静态方法都是通过函数装饰器的方式实现的;
- 实例方法需要传入self,类方法需要传入cls参数,静态方法无需传入self参数或者是cls参数(但不等同于不能传入参数)
注意:self参数和cls参数的区别,下文会提到。
下面分别尝试调用三个方法:
my_class = MyClass() # 实例化
my_class.instance_method() # 实例方法
my_class.class_method() # 类方法
my_class.static_method() # 静态方法
1️⃣当实例化时,my_class指向实例化对象:
2️⃣当调用实例方法(instance method)时,self参数指向的是刚刚实例化出的my_class实例对象:
3️⃣当调用类方法(class method)时,cls参数指向的是一开始定义的MyClass类对象(注意不是实例对象):
4️⃣当调用静态方法(static method)时:
本小节内容,主要区别了实例方法、类方法、静态方法的定义形式,以及区别了self、cls参数的指向对象。
注意:不管self参数,还是cls参数,都是一种约定俗成的用法,其实是可以使用其他的参数名代替。但是不建议使用其他参数名,毕竟代码不是只是写给自己看的。
三、再探实例方法、类方法、静态方法
上文都是通过实例化出的对象,对三种方法进行的调用,并且都得到了我们想要的结果;如果不通过实例化对象,而是直接通过类对象(Python中一切皆对象,包括类本身)调用,会有什么结果呢?
MyClass.instance_method() # 实例方法
MyClass.class_method() # 类方法
MyClass.static_method() # 静态方法
1️⃣当通过类对象调用实例方法时,直接报错,提示缺参数self。
因为点语法会将类对象MyClass传给instance_method()方法,但是instance_method()参数需要指向的是一个实例对象,而非类对象。
TypeError: static_method() missing 1 required positional argument: 'self'
2️⃣当通过类对象调用类方法时,这里的结果与通过实例对象调用是完全一样的。
Python官方文档的解释:It can be called either on the class (such asC.f()
) or on an instance (such asC().f()
). The instance is ignored except for its class. If a class method is called for a derived class, the derived class object is passed as the implied first argument.
大致意思,类方法可以通过类对象或者实例对象调用。如果是通过实例对象调用的,那么实例对象会被忽略,而是转而通过其类对象进行调用。类对象,会以参数形式传给类方法(点语法),作为类方法的第一个参数,也就是cls参数。
3️⃣当通过类对象调用静态方法时,这里的结果与通过实例对象调用是完全一样的。通过实例对象调用静态方法时,实例对象也会被忽略,而是通过其类对象进行调用,这一点与类方法的调用是一样的。
说明:为了简化所举的例子,本文中所定义的MyClass类并没有采用self或者cls之外的参数,三种方法都可以使用额外的参数,跟函数定义参数是一样的。
四、类方法使用场景
由于类方法无须创建实例对象调用,所以类方法的调用较实例方法更为灵活。以Django中View视图类源码举例:
class View(object):
"""
Intentionally simple parent class for all views. Only implements
dispatch-by-method and simple sanity checking.
"""
http_method_names = ['get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'trace']
def __init__(self, **kwargs):
"""
Constructor. Called in the URLconf; can contain helpful extra
keyword arguments, and other things.
"""
# Go through keyword arguments, and either save their values to our
# instance, or raise an error.
for key, value in six.iteritems(kwargs):
setattr(self, key, value)
@classonlymethod
def as_view(cls, **initkwargs):
"""
Main entry point for a request-response process.
"""
for key in initkwargs:
if key in cls.http_method_names:
raise TypeError("You tried to pass in the %s method name as a "
"keyword argument to %s(). Don't do that."
% (key, cls.__name__))
if not hasattr(cls, key):
raise TypeError("%s() received an invalid keyword %r. as_view "
"only accepts arguments that are already "
"attributes of the class." % (cls.__name__, key))
def view(request, *args, **kwargs):
self = cls(**initkwargs)
if hasattr(self, 'get') and not hasattr(self, 'head'):
self.head = self.get
self.request = request
self.args = args
self.kwargs = kwargs
return self.dispatch(request, *args, **kwargs)
view.view_class = cls
view.view_initkwargs = initkwargs
# take name and docstring from class
update_wrapper(view, cls, updated=())
# and possible attributes set by decorators
# like csrf_exempt from dispatch
update_wrapper(view, cls.dispatch, assigned=())
return view
def dispatch(self, request, *args, **kwargs