assert和hasattr,getattr,setattr

assert hasattr(self, 'initial_data'), (
    'Cannot call `.is_valid()` as no `data=` keyword argument was '
    'passed when instantiating the serializer instance.'
)

  

hasattr(self, 'initial_data')为真,则ok,为假,则抛出AssertionError

内容为后面的信息

 

hasattr(对象,属性或方法)

self是本类,initial_data判断类里有没有这个属性。

 

getattr(对象,属性或方法,默认值)

# 设定返回值_data,在if和elif中,如果没有get到_errors这个属性,则调用to_representation
if not hasattr(self, '_data'):
    if self.instance is not None and not getattr(self, '_errors', None):
        self._data = self.to_representation(self.instance)
    elif hasattr(self, '_validated_data') and not getattr(self, '_errors', None)
        self._data = self.to_representation(self.validated_data)
    else:
        self._data = self.get_initial()

  

posted @ 2019-08-02 18:16  jabbok  阅读(1499)  评论(0编辑  收藏  举报