如何在一些更改后更改Class()中的初始值

时间:2016-02-24 12:03:30

标签: python

我在课堂上有一些初始值 在最初,它将检查access_token是否为空,
需要致电get_access_token进行更新 但在更新后,我打印了值print "After change",self.access_token

它仍然是None
如何在更新self.oauth_objself.access_token ??

后更新值
class Client():

    def __init__(self):

        obj = Data.objects.get(username="tt")
        self.oauth_obj = obj
        self.url = self.oauth_obj.url
        self.username = self.oauth_obj.username
        self.password = self.oauth_obj.password
        self.access_token = self.oauth_obj.access_token
        self.refresh_token = self.oauth_obj.refresh_token

        print "========="
        print "Before change",self.access_token
        if not obj.access_token:
            self.get_access_token()
        print "After change",self.access_token
        print "========="


    def get_access_token(self):

        url =self.url
        payload = {
            'grant_type': 'password',
            'username': self.username,
            'password': self.password,
        }
        response = requests.post(url, auth=auth, data=payload)
        response_data = response.json()
        access_token = response_data["access_token"]
        refresh_token = response_data["refresh_token"]
        self.oauth_obj.access_token = access_token
        self.oauth_obj.refresh_token = refresh_token
        self.oauth_obj.save()

1 个答案:

答案 0 :(得分:2)

您正在创建局部变量。在get_access_token方法中,更改要分配给self的行:

def get_access_token(self):
    ...
    self.access_token = response_data["access_token"]
    self.refresh_token = response_data["refresh_token"]
    self.oauth_obj.access_token = self.access_token
    self.oauth_obj.refresh_token = self.refresh_token
    ...