Sunday, 15 September 2013

How to filter which attributes I want to delete in Python class?

How to filter which attributes I want to delete in Python class?

There are certain attributes from the class I allow to be deleted. But,
others are forbidden to be deleted.
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
This code does not work. What's wrong with the code? Both attributes are
still being deleted. I am using Python 3 by the way. __delattr__ does not
seem to work. Please note, I don't want to instantiate the class (I don't
want foo = klass(); del foo.a; / I want del klass.a;). Thanks.

No comments:

Post a Comment