Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python:在init中运行类的staticmethod?_Python_Oop - Fatal编程技术网

Python:在init中运行类的staticmethod?

Python:在init中运行类的staticmethod?,python,oop,Python,Oop,下面的内容让我怀疑我想要的是类还是模块 基本上,我正在构建一个解析器,一个API库 我的代码连接到的外部服务在每次发出请求时都需要一个令牌 我正在成功生成此令牌。但是,如果类的\uuuu init\uuuu中没有这个令牌,我不确定如何将它“赋予”给类实例 到目前为止,我的代码是: class MBParser(object): pass class SomeServiceParser(MBParser): '''instantiate and use me''' d

下面的内容让我怀疑我想要的是类还是模块

基本上,我正在构建一个解析器,一个API库

我的代码连接到的外部服务在每次发出请求时都需要一个令牌

我正在成功生成此令牌。但是,如果类的
\uuuu init\uuuu
中没有这个令牌,我不确定如何将它“赋予”给类实例

到目前为止,我的代码是:

class MBParser(object):
    pass

class SomeServiceParser(MBParser):

    '''instantiate and use me'''

    def __init__(self):
        self.token = _get_token()


    @staticmethod
    def _get_token():
      # code to get the token

您可以将每个需要新标记的函数包装在装饰器中,如下所示:

def new_token(func):
    def wrapper(self, *args, **kwargs):
        self.token = SomeParser._get_token()
        r = func(self, *args, **kwargs)
    return wrapper
我在
wrapper
方法中显式添加了一个
self
参数,因为类中的方法无论如何都需要这个参数。这样,我就可以访问
self.token
属性并将其设置为新值

可以按如下方式使用装饰器:

@new_token
def makeHTTPRequest(self, name):
    # ... make request and use self.token here

你看过你贴的东西了吗?从字面上讲,这在中国毫无意义English@MarcinOrlowski在我读到我的帖子之前,我认为这个评论是粗鲁的。我现在已经纠正了语法错误。你到底在问什么?它看起来相当模棱两可。我认为编写
SomeServiceParser非常好。\u获取\u token()
并通过调用类将not实例传递给该方法object@NChauhan我需要在我的类方法中发出
http
请求,这些请求需要令牌,我不想一遍又一遍地调用
\u get\u token()
,我明白了。你可以找个装修工来做这件事。讽刺的是,我写了一个虚拟版本来解释装饰者