我认为最好的解决办法是change your class hierarchy这样你就可以得到你想要的课程,没有任何花哨的技巧。
但是,如果你有一个很好的理由不这样做,你可以隐藏color
属性using a Descriptor.你需要使用新的样式类才能工作。
class A(object):
name = 7
description = 8
color = 9
class Hider(object):
def __get__(self,instance,owner):
raise AttributeError, "Hidden attribute"
def __set__(self, obj, val):
raise AttributeError, "Hidden attribute"
class B(A):
color = Hider()
然后你会得到一个AttributeError
当您尝试使用color
属性:
>>> B.color
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in __get__
AttributeError: Hidden attribute
>>> instance = B()
>>> instance.color
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in __get__
AttributeError: Hidden attribute
>>> instance.color = 3
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 6, in __set__
AttributeError: Hidden attribute
如果B是A的一个简化版本,为什么不上延伸,而不是其他的方式B,回合? – 2010-09-09 07:38:59