super方法

继承

__init__是python中的构造函数,用于属性的初始化。

如果在子类中定义了构造函数,python默认不会调用父类的构造函数,父类里的属性就不会集成到子类。

super

用于调用父类(超类)的一个方法

class Person():
    def __init__(self, name='jab'):
        self.name = name

class Mate(Person):
    def __init__(self, age):
        self.age = age

class MateS(Person):
    def __init__(self, age):
        self.age = age
        super().__init__()
#Mate类无法调用父类的name属性
#MateS类中使用了super方法,可以调用父类的name属性

  

 

drf 序列化源码中的例子

class Field:
    _creation_counter = 0

    default_error_messages = {
        'required': _('This field is required.'),
        'null': _('This field may not be null.')
    }
    default_validators = []
    default_empty_html = empty
    initial = None

    def __init__(self, read_only=False, write_only=False,
                 required=None, default=empty, initial=empty, source=None,
                 label=None, help_text=None, style=None,
                 error_messages=None, validators=None, allow_null=False):
        self._creation_counter = Field._creation_counter
        Field._creation_counter += 1

  

class BaseSerializer(Field):

    def __init__(self, instance=None, data=empty, **kwargs):    #初始化,传入instance,data参数
        self.instance = instance    #instance,data给到self
        if data is not empty:
            self.initial_data = data
        self.partial = kwargs.pop('partial', False)     #将额外的字典参数中,partial,context给到self,如果没有,给出默认值
        self._context = kwargs.pop('context', {})
        kwargs.pop('many', None)    #将many这个key删除
        super().__init__(**kwargs)  #继承父类的其余属性

  

子类重写父类方法时使用super

class BaseSerializer():
    def __init__(self, value):
        self.value = value

    @property
    def square(self):
        self._square = self.value * self.value
        return self._square

class Serlalizer(BaseSerializer):
    @property
    def square(self):
        ret = super().square
        return 'square=%d' %ret

serializer = Serlalizer(10)
print(serializer.square)

  

    #父类
    @property
    def data(self):
        if hasattr(self, 'initial_data') and not hasattr(self, '_validated_data'):
            msg = (
                'When a serializer is passed a `data` keyword argument you '
                'must call `.is_valid()` before attempting to access the '
                'serialized `.data` representation.\n'
                'You should either call `.is_valid()` first, '
                'or access `.initial_data` instead.'
            )
            raise AssertionError(msg)

        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()
        return self._data


    #子类
    @property
    def data(self):
        ret = super().data
        return ReturnDict(ret, serializer=self)

  

 

posted @ 2019-08-01 17:35  jabbok  阅读(511)  评论(0编辑  收藏  举报