2

我允许删除类中的某些属性。但是,禁止删除其他人。

class klass:
    a = 1
    b = 2

    def __delattr__(cls, attr):
        if attr=='a':
            pass # go ahead, delete attribute a
        elif attr=='b':
            raise TypeError("Bad boy/girl, you shouldn't delete attribute b")

del klass.a
del klass.b

此代码不起作用。代码有什么问题?这两个属性仍在被删除。顺便说一句,我正在使用 Python 3。__delattr__似乎不起作用。请注意,我不想实例化该类(我不想foo = klass(); del foo.a;/我想要del klass.a;)。谢谢。

4

3 回答 3

6

__delattr__()处理类实例属性的删除。您的代码尝试删除类本身的属性。

以下按预期工作:

class klass(object):

   def __init__(self):
      self.a = 1
      self.b = 2

   def __delattr__(self, attr):
      if attr == 'b':
         raise TypeError("Bad boy/girl, you shouldn't delete attribute b")
      else:
         super(klass, self).__delattr__(attr)

k = klass()
del k.a
del k.b
于 2013-09-15T07:08:50.613 回答
1

使用元类:

class Meta(type):
   _a = 1
   @property
   def a(self):
      return self._a

   @a.setter
   def a(self, value):
       self._a = value

class klass(metaclass=Meta):
    b = 2

演示:

>>> klass.a, klass.b
(1, 2)
>>> del klass.a
Traceback (most recent call last):
  File "<ipython-input-22-b06d010031d5>", line 1, in <module>
    del klass.a
AttributeError: can't delete attribute

>>> del klass.b
于 2013-09-15T07:39:34.933 回答
0

我自己找到了答案。该答案基于 Ashwini Chaudhary 和 NPE 的答案。我赞成你们两个!再次感谢。

class Meta(type):
    def __delattr__(cls, attr):
        if attr=='b':
            raise TypeError("Bad boy/girl, you shouldn't delete attribute b")
        elif attr=='a':
            super(Meta, cls).__delattr__(attr)

class klass(metaclass=Meta):
    a = 1
    b = 2

print(hasattr(klass, 'a'))  # True
del klass.a
print(hasattr(klass, 'a'))  # False
del klass.b  # throws TypeError exception
于 2013-09-16T13:59:08.980 回答