gpt4 book ai didi

python - 覆盖的属性访问不起作用(如预期)

转载 作者:行者123 更新时间:2023-12-01 00:00:07 24 4
gpt4 key购买 nike

以下模块的主要目标是为某些名称提供一种“常量”语义。

class ConstantError(Exception):

def __init__(self, msg):
self._msg = msg


class Constant(object):

def __init__(self, name):
self._name = name

def __get__(self, instance, owner):
return instance._content[self._name]

def __set__(self, instance, value):
raise ConstantError, 'Illegal use of constant'


class Constants(object):

def __init__(self, content):
self._content = content
for k in self._content:
setattr(self, k, Constant(k))

num_const = Constants({
'one': 1,
'two': 2
})

使用时:

>>> from const import *
>>> dir(num_const)
['__class__', '__delattr__', '__dict__', '__doc__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', '__weakref__', '_content', 'one', 'two']

所以 onetwo 存在,但属性访问是diappointing:

>>> num_const.one
<const.Constant object at 0x7faef4871710>
>>>

在这种情况下我希望 1 。我哪里错了?

最佳答案

描述符协议(protocol)仅适用于类的属性,而不适用于类实例的属性。请参阅How-To Guide for Descriptors

关于python - 覆盖的属性访问不起作用(如预期),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1874043/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com