【发布时间】:2010-11-24 10:17:14
【问题描述】:
由于python没有常量的概念,如果更新'constant'属性是否可以引发异常?如何?
class MyClass():
CLASS_CONSTANT = 'This is a constant'
var = 'This is a not a constant, can be updated'
#this should raise an exception
MyClass.CLASS_CONSTANT = 'No, this cannot be updated, will raise an exception'
#this should not raise an exception
MyClass.var = 'updating this is fine'
#this also should raise an exception
MyClass().CLASS_CONSTANT = 'No, this cannot be updated, will raise an exception'
#this should not raise an exception
MyClass().var = 'updating this is fine'
任何将 CLASS_CONSTANT 更改为类属性或实例属性的尝试都应该引发异常。
将 var 更改为类属性或实例属性不应引发异常。
【问题讨论】:
-
Alex Martelli 和 Ants Aasma 的解决方案都有效。我选择了 Alex Martelli 的解决方案,因为它可以在子类中使用,但一些开发人员可能也更喜欢 Ants Aasma 的风格。
标签: python exception attributes constants