Prevent overriding property for class methods in Python?
I have the following code:
class Test(object):
_spam = 42
@classmethod
def get_spam(cls):
cls._spam
@classmethod
def set_spam(cls, value):
cls._spam = value
spam = property(get_开发者_如何学Pythonspam, set_spam)
print Test.spam
Test.spam = 24
print Test.spam
The output is:
<property object at 0x01E55BD0>
24
Is there any way to prevent the setting of Test.spam
from overriding the property? I don't want to use Test.spam
to set the value of Test._spam
. The setter and getter have to remain as class methods, and I do not want to have to call Test.set_spam
.
The output should be:
<property object at 0x01E55BD0>
<property object at 0x01E55BD0>
I suppose this stops developers from accidentally overwriting Test
's spam property. Is that why you want this? I not sure that is a good idea (what if a developer wants to override the spam property? why throw up roadblocks?), but...
You could use a metaclass. If you don't supply a setter for the metaclass's property, then Test.spam
will raise an AttributeError:
class MetaTest(type):
@property
def spam(cls):
return cls._spam
class Test(object):
__metaclass__=MetaTest
_spam = 42
@classmethod
def get_spam(cls):
cls._spam
@classmethod
def set_spam(cls, value):
cls._spam = value
spam = property(get_spam, set_spam)
print Test.spam
# 42
But
Test.spam = 24
raises
AttributeError: can't set attribute
精彩评论