使用python属性,并且仍然能够显式地设置值

2024-04-27 03:36:30 发布

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

我试图理解@property decorator是如何工作的。你知道吗

这里我使用方法y作为字段x的属性

在self.x属性有了属性之后,是否意味着我们不能显式地设置值。。你知道吗

我以为上一条语句-->;c.x=2在变量上设置了property方法之后就不起作用了?你知道吗

class C(object):
    def __init__(self):
        self.x = 0
        self.list = [1,2,3,4,10]
    @property
    def y(self):
        print 'getting'
        self.x = sum(self.list) 
        return self.x

    @y.setter
    def y(self, value):
        print 'setting'
        self.x = value

if __name__ == '__main__':
    c = C()
    print 'Value of c.y=',c.y
    print '-'*80
    c.y = 50
    print '-'*80
    print c.y
    print '-'*80
    if c.y >5:
        print 'Hi'

Tags: 方法gtselfif属性objectinitvalue
3条回答

你不能禁止改变属性直接使用属性装饰,但你可以这样做的把戏,我认为

class A(object):
    def __init__(self):
        self.x = 0
    @property
    def x(self):
        return self.__dict__['x']
    @x.setter
    def x(self, value):
        self.__dict__['x']=value

这将允许您实现所描述的行为

在Python中,通过名称损坏对private instance variables的支持有限

为了避免暴露x,需要两个前导下划线,即__x

总是可以显式地设置x。你知道吗

class Foo(object):
    def __init__(self):
        self.x = 1
        self.lst = [1,2,3]

    @property
    def y(self):
        self.x = sum(self.lst)
        return self.x

    @y.setter
    def y(self,value):
        self.x = value


f = Foo()
print f.y #6
print f.x #6
f.x = 3
print f.x #3
print f.y #6
print f.x #6

问题是,在本例中,调用getter(y)也设置了x属性的值,因此如果您通过y进行所有更改,您永远不会看到x的更改,因为查看y的行为会更改x。你知道吗

您可以尝试绕过该限制的一种方法是:

class Foo(object):
    def __init__(self):
        self.x = None
        self.lst = [1,2,3]

    @property
    def y(self):
        return sum(self.lst) if self.x is None else self.x

    @y.setter
    def y(self,value):
        self.x = value

现在,如果显式地为x(或y)设置一个值,该值将一直保留,直到您将其设置回None,如果您真的需要,甚至可以在另一个用@y.deleter修饰的函数中执行。你知道吗

相关问题 更多 >