简体   繁体   English

为什么在使用django视图时跨python范围共享变量

[英]Why are variables shared across scopes in python when using django views

Please Note this is a very Django specific question, so if you know the Django Rest Framework you will understand it 请注意,这是一个非常特定于Django的问题,因此,如果您知道Django Rest Framework,您将理解它

So I have a view in Django rest framework with an update function over ridden and a _has_permission helper function 所以我在Django rest框架中有一个视图,该视图具有覆盖的更新功能和_has_permission helper函数

def update(self, request, *args, **kwargs):
        permission, message = self._has_permission(data=request.data)
        if not permission:
            return Response({'error': message}, status=status.HTTP_403_FORBIDDEN)

        return super().update(request, *args, **kwargs)



    def _has_permission(self, data):
        """
       Resolves if the logged in user has permission to update the data given the type of data
       :param data:
       :return:
       """


        data['user_type'] = data['user_type'] if ('user_type' in data and data['user_type']) else None

        ....
        some checks
        ....
        return True, 'Has Permission'

In the case where the function _has_permission() sees that 'user_type' is not in data, it sets data['user_type'] = None in the function, but when it comes out request.data['user_type'] now exists and becomes None as well 在函数_has_permission()看到'user_type'不在数据中的情况下,它在函数中设置data ['user_type'] = None,但当它出现时request.data ['user_type']现在存在并变为也没有

How is this dictionary being shared across two different scopes. 如何在两个不同的范围内共享此词典。 I thought functions have their own scopes 我认为功能有自己的范围

Contrary to your assertion, this is not at all specific to DRF, but a very general Python principle. 与您的断言相反,这根本不是 DRF特有的,而是非常通用的Python原理。

Passing any argument to a function always passes the object itself. 将任何参数传递给函数始终会传递对象本身。 If you then mutate that object in the function, all other references to that object will see that modification, because they remain references to the same object. 如果随后在函数中对该对象进行了更改,则对该对象的所有其他引用都将看到该修改,因为它们仍然是对同一对象的引用。

By default, in Python, all args are passed by reference (or a kind of), which mean, you are passing a reference to the object, not a copy, so if you alter the object inside a function, you are affecting the object itself, not a copy of it. 默认情况下,在Python中,所有args都是通过引用(或某种引用)传递的,这意味着您正在传递对对象的引用,而不是副本,因此,如果您在函数内部更改对象,则会影响该对象本身,而不是副本。 You can see more details at http://robertheaton.com/2014/02/09/pythons-pass-by-object-reference-as-explained-by-philip-k-dick/ 您可以在http://robertheaton.com/2014/02/09/pythons-pass-by-object-reference-as-explained-by-philip-k-dick/中查看更多详细信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM