在类对象中,如何自动更新属性? [英] In class object, how to auto update attributes?

查看:59
本文介绍了在类对象中,如何自动更新属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有多个相关属性的类,例如:

I have a class which has multiple attributes that are related, for example:

class SomeClass:
    def __init__(self, n=0):
        self.list = range(n)
        self.listsquare = [ x**2 for x in self.list ]

如果我正常地创建一个对象,就不会有问题,

If I make an object normally that would no problem, with

a = SomeClass(10)

我将获得2个列表,分别为a.lista.listsquare.

I will get 2 lists, a.list and a.listsquare.

现在,如果我想先创建一个空对象,并为其分配一个属性,那么我希望其他属性能够自动更新,例如,如果我这样做

Now if I want to make a empty object first, and assign one attribute to it, I want the other attributes to be automatically updated, for example if I do

b = SomeClass()
b.list = range(5,10)

我希望自动更新b.listsquare,并且也希望自动更新(分配b.listsquare和自动更新b.list).这可能吗? Class 是否是正确的选择?

I want b.listsquare to be automatically updated, and also the other way around (assign b.listsquare and auto update b.list). Is this possible? Is Class the right choice for this?

谢谢大家,但是我对所有不同的答案完全不知所措.谁能提供一个完整的解决方案,让我可以学习编写自己的解决方案?

Thanks to you all, but I'm completely overwhelmed by all the different answers. Can anyone give a complete solution so I can learn write my own?

我想实现一个具有3个属性lengthlistlistsquare的类Foo:

I would like to achieve a class Foo with 3 attributes length, list and listsquare such that:

  1. 如果我执行a = Foo(3),我会得到a.length = 3a.list = [0, 1, 2]a.listsquare = [0, 1, 4].
  2. 如果我执行b = Foo().list = [5, 6],我会得到b.length = 2b.listsquare = [25, 36].
  3. 如果我执行c = Foo().listsquare = [4, 9],我会得到c.length = 2c.list = [2, 3].
  1. If I do a = Foo(3), I get a.length = 3, a.list = [0, 1, 2], a.listsquare = [0, 1, 4].
  2. If I do b = Foo().list = [5, 6], I get b.length = 2, b.listsquare = [25, 36].
  3. If I do c = Foo().listsquare = [4, 9], I get c.length = 2, c.list = [2, 3].

推荐答案

如果您要查找的是由于另一个属性的更新而导致更新一个属性(而不是重新计算访问时下游属性的值),请使用use属性设置者:

if updating one property due to an update on another property is what you're looking for (instead of recomputing the value of the downstream property on access) use property setters:

class SomeClass(object):
    def __init__(self, n):
        self.list = range(0, n)

    @property
    def list(self):
        return self._list
    @list.setter
    def list(self, val):
        self._list = val
        self._listsquare = [x**2 for x in self._list ]

    @property
    def listsquare(self):
        return self._listsquare
    @listsquare.setter
    def listsquare(self, val):
        self.list = [int(pow(x, 0.5)) for x in val]

>>> c = SomeClass(5)
>>> c.listsquare
[0, 1, 4, 9, 16]
>>> c.list
[0, 1, 2, 3, 4]
>>> c.list = range(0,6)
>>> c.list
[0, 1, 2, 3, 4, 5]
>>> c.listsquare
[0, 1, 4, 9, 16, 25]
>>> c.listsquare = [x**2 for x in range(0,10)]
>>> c.list
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

这篇关于在类对象中,如何自动更新属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆