class OurAtt():
def __init__(self):
self.Log = False
def setLog(self):
self.Log = True
def clearLog(self):
self.Log = False
class OurClass(object):
def __init__(self):
self.__OurAtt = OurAtt()
@property
def OurAtt(self):
return self.__OurAtt
@OurAtt.setter
def OurAtt(self, val):
raise Exception("can't modify the attribute" )
x = OurClass()
x.OurAtt.setLog()
print x.OurAtt.Log # print True
x.OurAtt.Log = False
print x.OurAtt.Log # sets to False Aim set this through function call x.OurAtt.setLog() I want to restrict the access, something like private variable.
最后的目标是Log应该是OurAttr的属性,并且应该受到getter和setter或属性的保护。这就像是属性的嵌套。等级制度应该像对象.OurAttr.Log在
我研究并得到以下链接。在
Python: multiple properties, one setter/getter
但这并没有达到我的目的。在
实际上,我对getter、setter和properties还不熟悉。提前谢谢
我相信你把问题复杂化了。如果要阻止对OurAtt属性的访问,
@property
修饰符应该与OurAtt
一起使用。OurAtt
类的实例将始终实现这种受保护的访问行为,包括当它们是OurClass
的成员时。您不需要对OurClass
中的@property
修饰符执行任何操作,除非您希望阻止修改该类的成员。在我想,这就是你想要达到的目标。它运行在2.7以下-如果您使用的是早期版本,您的里程数可能会有所不同。在
输出为:
^{pr2}$相关问题 更多 >
编程相关推荐