如何使用方法更改类属性? [英] How to change class attributes using a method?
问题描述
我知道这可能是一个愚蠢的问题,但是我还没有找到解决方案.
我有一个具有一些默认属性的Django模型类,并且我想通过调用一个函数来更改complete变量的值:
class目标(models.Model):文字= models.CharField(max_length = 500)日期= models.DateTimeField(auto_now = True)完成=错误def set_complete_true():完成=正确
但是在调用set_complete_true()之后,完整变量仍然为False,不会更改.
提前谢谢!
实例函数(大多数函数是实例函数)具有一个特殊参数,该参数始终是第一个一种叫做 self
.它是对您用来调用该函数的对象的引用.例如,如果您调用 some_instance.foo()
,则将 foo
与 some_instance
一起作为 self
来调用./p>
因此,您需要添加 self
参数,并将 self.complete
设置为 True
:
class目标(models.Model):文字= models.CharField(max_length = 500)日期= models.DateTimeField(auto_now = True)完成=错误def set_complete_true(自我):自我. complete = True
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!
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
这篇关于如何使用方法更改类属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!