python中的attrs是什么?
大家讲道理
大家讲道理 2017-04-17 13:43:30
0
2
1417
from rest_framework import serializers

class CommentSerializer(serializers.Serializer):
    email = serializers.EmailField()
    content = serializers.CharField(max_length=200)
    created = serializers.DateTimeField()

    def restore_object(self, attrs, instance=None):
        """
        Given a dictionary of deserialized field values, either update
        an existing model instance, or create a new model instance.
        """
        if instance is not None:
            instance.email = attrs.get('email', instance.email)
            instance.content = attrs.get('content', instance.content)
            instance.created = attrs.get('created', instance.created)
            return instance
        return Comment(**attrs)

比如,这其中的attrs是?

大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

Antworte allen(2)
迷茫

这是python的参数列表,两个星号是可变参数。
restore_object接收到的attrs参数是dict类型,传递到Comment函数的时候前面加两个星号转成可变参数列表。
比如

attrs = {'a':1, 'b':2}

Comment函数实际的调用会变成:

Comment(a=1, b=2)

参考:http://n3xtchen.github.io/n3xtchen/python/2014/08/08/python---args-and-kwargs/

阿神

attr 是函数的参数 具体是啥要看你自己的定义了

Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!