python - 在 python 中更新 'constant' 属性时引发异常

标签 python exception attributes constants

由于 python 没有常量的概念,如果更新“常量”属性是否可能引发异常?如何?

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 作为类属性或实例属性更改不应引发异常。

最佳答案

在每个类中自定义 __setattr__(例如,@ainab 的回答指向我的旧食谱以及其他答案),只能停止对 INSTANCE 属性的分配,而不是对 CLASS 属性的分配。因此,现有的答案都不能真正满足您的要求。

如果您要求的实际上正是您想要的,您可以诉诸自定义元类和描述符的某种组合,例如:

class const(object):
  def __init__(self, val): self.val = val
  def __get__(self, *_): return self.val
  def __set__(self, *_): raise TypeError("Can't reset const!")

class mcl(type):
  def __init__(cls, *a, **k):
    mkl = cls.__class__
    class spec(mkl): pass
    for n, v in vars(cls).items():
      if isinstance(v, const):
        setattr(spec, n, v)
    spec.__name__ = mkl.__name__
    cls.__class__ = spec

class with_const:
  __metaclass__ = mcl

class foo(with_const):
  CLASS_CONSTANT = const('this is a constant')

print foo().CLASS_CONSTANT
print foo.CLASS_CONSTANT
foo.CLASS_CONSTANT = 'Oops!'
print foo.CLASS_CONSTANT

这是非常高级的东西,所以您可能更喜欢其他答案中建议的更简单的 __setattr__ 方法,尽管它不符合您规定的要求(即,您可以合理地选择削弱您的要求,以便为了获得简单性;-)。但是这里的技术可能仍然很有趣:自定义描述符类型 const 是另一种方式(恕我直言,比在每个需要一些常量的类中重写 __setattr__ 并使所有属性常量而不是挑选和选择...)以阻止对实例属性的分配;其余代码是关于自定义元类的,它创建了自己的独特的每个类子元类,以便最充分地利用所述自定义描述符并实现您特别要求的确切功能。

关于python - 在 python 中更新 'constant' 属性时引发异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1358711/

相关文章:

python - 即使 Python 脚本没有焦点,也会监听快捷键(例如 WIN+A)

python - 使用 **kwds 时避免 pandas 改变绘图颜色

python - 距离矩阵的树状图或其他图

java - 在finally block 中处理异常

attributes - @nogc 属性是否在 d 中实现?

sockets - 有人可以解释一下 "from socket import example"和 "import socket"之间的区别吗?

colors - 将颜色属性添加到 NetworkX 上的节点以导出到 Gephi

python - 在 Django Rest Framework Views 中测试身份验证——测试时无法进行身份验证

Java - ClassNotFoundException : java.net.http.HttpClient

exception - 在Dartium刷新会在websocket服务器中引发SocketException