Set a Read-Only Attribute in Python?

前端 未结 2 1582
挽巷
挽巷 2020-12-03 08:14

Given how dynamic Python is, I\'ll be shocked if this isn\'t somehow possible:

I would like to change the implementation of sys.stdout.write.

I

2条回答
  •  借酒劲吻你
    2020-12-03 08:24

    Despite Python mostly being a dynamic language, there are native objects types like str, file (including stdout), dict, and list that are actually implemented in low-level C and are completely static:

    >>> a = []
    >>> a.append = 'something else'
    Traceback (most recent call last):
      File "", line 1, in 
    AttributeError: 'list' object attribute 'append' is read-only
    
    >>> a.hello = 3
    Traceback (most recent call last):
      File "", line 1, in 
    AttributeError: 'list' object has no attribute 'hello'
    
    >>> a.__dict__  # normal python classes would have this
    Traceback (most recent call last):
      File "", line 1, in 
    AttributeError: 'list' object has no attribute '__dict__'
    

    If your object is native C code, your only hope is to use an actual regular class. For your case, like already mentioned, you could do something like:

    class NewOut(type(sys.stdout)):
        def write(self, *args, **kwargs):
            super(NewOut, self).write('The new one was called! ')
            super(NewOut, self).write(*args, **kwargs)
    sys.stdout = NewOut()
    

    or, to do something similar to your original code:

    original_stdoutWrite = sys.stdout.write
    class MyClass(object):
        pass
    sys.stdout = MyClass()
    def new_stdoutWrite(*a, **kw):
        original_stdoutWrite("The new one was called! ")
        original_stdoutWrite(*a, **kw)
    sys.stdout.write = new_stdoutWrite
    

提交回复
热议问题