python中属性与setter和getter的嵌套

2024-04-25 06:56:17 发布

您现在位置:Python中文网/ 问答频道 /正文

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还不熟悉。提前谢谢


Tags: theselflogfalsetrue属性initdef
1条回答
网友
1楼 · 发布于 2024-04-25 06:56:17

我相信你把问题复杂化了。如果要阻止对OurAtt属性的访问,@property修饰符应该与OurAtt一起使用。OurAtt类的实例将始终实现这种受保护的访问行为,包括当它们是OurClass的成员时。您不需要对OurClass中的@property修饰符执行任何操作,除非您希望阻止修改该类的成员。在

我想,这就是你想要达到的目标。它运行在2.7以下-如果您使用的是早期版本,您的里程数可能会有所不同。在

class OurAttr(object):
    def __init__(self):
        self._log = False

    @property
    def log(self):
        return self._log

    @log.setter
    def log(self, value):
        raise AttributeError("Cannot set 'log' attribute directly.")

    @log.deleter
    def log(self):
        raise AttributeError("Cannot delete 'log' attribute directly.")

    def setLog(self):
        self._log = True
        print "Log is", self._log

    def clearLog(self):
        self._log = False
        print "Log is", self._log

class OurClass(object):
    def __init__(self):
        self.OurAttr = OurAttr()

oc = OurClass()
oc.OurAttr.setLog()
oc.OurAttr.clearLog()
oc.OurAttr.log = False   # Raises exception

输出为:

^{pr2}$

相关问题 更多 >