How to change class attributes using a method?

自作多情 提交于 2021-01-28 03:18:01

问题


I know this is maybe a dumb question but I haven't found a solution yet.

I have a Django model class who has some default attributes, and I want to change the value of the complete variable by calling a function:

class Goal(models.Model):
    text = models.CharField(max_length=500)
    date = models.DateTimeField(auto_now=True)
    complete = False

    def set_complete_true():
        complete = True

But after calling set_complete_true() the complete variable still False, doesn't change.

Thanks in advance!


回答1:


An instance function (most functions are instance functions) has a special parameter that is always the first one called self. It is a reference to the object with which you call the function. For example if you call some_instance.foo(), then foo is called with as self the some_instance.

You thus need to add the self parameter, and set the self.complete to True:

class Goal(models.Model):
    text = models.CharField(max_length=500)
    date = models.DateTimeField(auto_now=True)
    complete = False

    def set_complete_true(self):
        self.complete = True



回答2:


I dont know Django classes, but I believe this is worth a shot:

class Goal(models.Model):
    text = models.CharField(max_length=500)
    date = models.DateTimeField(auto_now=True)
    complete = False

    def set_complete_true(self):
        self.complete = True

a = Goal()
a.set_complete_true()
print(a.complete) # should be true now


来源:https://stackoverflow.com/questions/50392787/how-to-change-class-attributes-using-a-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!