我可以绕过将自我对象传递给python类方法吗?

问题描述 投票:1回答:1

我正在使用Google课堂api,并且函数的参数之一需要回调。

def callback(request_id, response, exception):
    if exception is not None:
        print 'Error adding user "{0}" to the course course: {1}'.format(
            request_id, exception)
    else:
        print 'User "{0}" added as a student to the course.'.format(
            response.get('profile').get('name').get('fullName'))

在我的情况下,该方法在类内部,并且我知道每个python方法都应使用一个self对象,但是在这种情况下,此函数将具有特定的参数,我不确定如何传递self对象,还是应该忽略self?问题是我计划在函数内部使用self。有什么想法吗?

python self google-classroom python-class
1个回答
1
投票

我认为我了解您的困境。继续并包括self作为第一个参数,因为Python每次调用callback()时都会隐式传递它。所有其他位置参数(request_idresponseexception)将不受方法的参数定义中包含self的影响。即:

def callback(self, request_id, response, exception):
    # ...

[如果您不打算在self方法(现在是一个函数)中使用callback对象,那么您可以在函数的定义上使用@staticmethod装饰器,但是如果我直接关注您,这里不是这种情况。

© www.soinside.com 2019 - 2024. All rights reserved.