关于类、方法、对象(实例):静态方法

类里面的方法有3种:类的实例方法(平时常用的带有self的方法)、静态方法(@staticmethod )、类方法(@classmethod)

这里主要看一下类的实例方法和静态方法的区别:

(1)实例方法只能被实例对象调用,第一个参数必须要默认传实例对象,一般习惯用self;

(2)静态方法(由@staticmethod装饰的方法)、类方法(由@classmethod装饰的方法),可以被类或类的实例对象调用;


先看如下代码

其实上述代码中的get_request()和post_request()方法可以写为静态方法(用pycharm的应该会见到提示,建议你这个方法改为静态方法,其实如果都按照实例方法来写的话,不改也不影响调用),因为这里并不需要通过实例来调用这两个方法,它们只是做一些逻辑处理(处理get请求或post请求)

修改后如下:

# encoding: utf-8

import requests
import json

class RunMethod:

    @staticmethod   # 构造为静态方法后,既可以通过类的命名空间调用,也可以通过实例调用,即self
    def get_request(url, data):
        r = requests.get(url=url, params=data)
        re = r.json()
        return json.dumps(re, indent=2, ensure_ascii=False)

    def post_request(url, data):   # 不构造为静态方法,不能通过self调用,需要通过类的命名空间调用
        r = requests.post(url=url, data=data)
        re = r.json()
        return json.dumps(re, indent=2, ensure_ascii=False)

    def run_main(self, method, url, data):
        if method == "GET":
            result = RunMethod.get_request(url, data)  # 通过类名调用(类的命名空间)
# result = self.get_request(url, data) # 通过实例调用
else: result = RunMethod.post_request(url, data) # 因为post_request()只是一个普通函数,不是静态方法和实例方法,所以只能通过类名调用 return result if __name__ == "__main__": url = "http://localhost:8088/ApprExclusiveInterface/api/enterprise/info/consult/save.v" data = { 'clientCode': '', 'topic': '测试接口', 'content': '测试接口', 'resrcType': 0 } r = RunMethod() # 需要注意的是如果类名后加上了(),表示对类进行了实例化 t = r.run_main("GET", url, data) print(t)
print(RunMethod.get_request(url, data)) # 直接通过类名调用

 值得注意的是,假如我们在一个类下定义了2个方法A,B,其中A既不是静态方法,也不是类(实例)方法,那么B在调用A时,或者在类外面调用类中的A方法时,必须使用类名来调用(即类的命名空间),形如:Class.A(),不过实际上并没有人这样干就是了(在类里面要么构造静态方法,要么构造类方法)

参考:https://zhuanlan.zhihu.com/p/21101992


2018-05-08 22:40:00

原文地址:https://www.cnblogs.com/hanmk/p/9011509.html