0

如何防止 Python 类方法被错误地更改?是否有某种“写保护”?

例子:

class bar():

    def blob(self):
        return 2

if __name__ == "__main__":

    foo = bar()
    print(foo.blob()) # Returns 2

    foo.blob = 1 # Overwrites the method "blob" without a warning!
                 # foo.blob returns 1, foo.blob() is not callabele anymore :( 

    foo.blib = 1 # Is also possible

    print(foo.blob)
    print(foo.blob())

当我调用此脚本时返回:

2
1
Traceback (most recent call last):
  File "blob.py", line 18, in <module>
    print(foo.blob())
TypeError: 'int' object is not callable

我宁愿得到警告。

4

0 回答 0