我有以下模型(这里,我们使用的是class属性):
class Foo(models.Model):
...
def some_function(self, some_condition):
if some_condition:
# Do something
class Bar(models.Model):
...
foo = models.ForeignKey(Foo)
_some_condition = False # Class attribute
def save(self, *args, **kwargs):
# Do something that sets the `_some_condition` class
# attribute based on some conditions
self.foo.some_function(self._some_condition)
super(Bar, self).save(*args, **kwargs)
简而言之,我的Bar
类具有名为_some_condition
的类属性。这是在save函数中设置的,然后用于调用Foo
类的some_function()
方法。
我还可以重写__init__()
方法并将_some_condition
设置为实例属性。像这样(在这里,我们使用实例属性):
class Bar(models.Model):
...
def __init__(self, *args, **kwargs):
super(Bar, self).__init__(*args, **kwargs)
self._some_condition = False # Instance attribute
...
两者之间有什么区别?我通常对Python中的类和实例属性感到困惑。
在同一个模型上完成两种操作并在外壳中对其进行测试之后,看来类属性和实例属性之间根本没有区别。谁能解释一下?以下是我用来测试两种方式的代码:
class MyClass(models.Model):
name = models.CharField(max_length=255)
_class_attr = ''
def __init__(self, *args, **kwargs):
super(MyClass, self).__init__(*args, **kwargs)
self._instance_attr = ''
def save(self, *args, **kwargs):
# Update both before saving
self._class_attr = 'Class attribute'
self._instance_attr = 'Instance attribute'
super(MyClass, self).save(*args, **kwargs)
结果:
>>> from myapp.models import MyClass
>>> MyClass.objects.create(name='first')
<MyClass: MyClass object (1)>
>>> MyClass.objects.create(name='second')
<MyClass: MyClass object (2)>
>>> first = MyClass.objects.get(pk=1)
>>> second = MyClass.objects.get(pk=2)
>>> first._class_attr
''
>>> first._instance_attr
''
>>> second._class_attr
''
>>> second._instance_attr
''
>>> first.save()
>>> first._class_attr
'Class attribute'
>>> first._instance_attr
'Instance attribute'
>>> second._class_attr
''
>>> second._instance_attr
''