Can I convert a namespace object from mutable to immutable?

后端 未结 2 1998
情深已故
情深已故 2021-01-28 22:20

I receive a namespace object from command line arguments. And I don\'t want to modify it. Can I do that or do you have some ideas?

# -*- coding: utf-8 -*-

impo         


        
2条回答
  •  孤城傲影
    2021-01-28 22:46

    You can redefine __setattr__ in your mutable_namespace:

    class NotMutableException(Exception):pass
    
    class SomeObject(object):
        def init(self):
            self.x = 10
            self.y = 20
    
    some_obj = SomeObject()
    some_obj.z = 30
    
    def not_setattr(self, name, value):
        raise NotMutableException
    
    type(some_obj).__setattr__ = not_setattr
    
    some_obj.a = 1000
    

提交回复
热议问题