【问题标题】:Update dynamically dependent object attributes after mutation突变后动态更新依赖对象属性
【发布时间】:2021-10-12 14:37:43
【问题描述】:

我们以this classical solution的依赖对象属性更新问题为例:

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]

但是,如果我们改变属性list 而不是将其设置为新值呢?:

>>> c.list[0] = 10
>>> c.list
[10, 1, 2, 3, 4, 5, 6, 7, 8, 9]  # this is ok
>>> c.listsquare
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]  # we would like 100 as first element

我们希望 listsquare 属性相应地更新,但事实并非如此,因为当我们更改 list 属性时不会调用设置器。

当然,我们可以在修改属性后通过显式调用 setter 来强制更新,例如:

>>> c.list[0] = 10
>>> c.list = c.list. # invoke setter
>>> c.listsquare
[100, 1, 4, 9, 16, 25, 36, 49, 64, 81]

但是对于用户来说它看起来有些麻烦且容易出错,我们希望它隐式发生。

当另一个 mutable 属性被修改时,更新属性的最 Pythonic 方式是什么。对象如何知道他的某个属性已被修改?

【问题讨论】:

  • 你必须使用一种特殊的可变类型来对这些事情做出反应。这似乎不是一个答案,但它提出了一个更具体的问题。
  • @DavisHerring 您对“对此类事情做出反应的特殊可变类型”有什么想法?你能详细说明一下吗?
  • 例如,您自己的序列类型会更新其__setitem__ 中的相反编号。对于实际使用,您必须实现许多功能(例如popremove,如果您想要整个list 接口)。让自定义类型提供一个底层数据存储的两个视图可能会更容易。

标签: python class properties attributes


【解决方案1】:

因此,正如 Davis Herring 在 cmets 中所说,这是非常可能的,但几乎没有那么干净。本质上,您必须构建自己的自定义数据结构,以并行维护两个列表,每个列表都知道另一个列表,因此如果一个更新,另一个也会更新。下面是我做这件事的镜头,嗯,比预期的要长一点。似乎有效,但我还没有全面测试过。

我在这里选择从collections.UserList 继承。另一种选择是从collections.abc.MutableSequence 继承,与UserList 相比,它有各种优点和缺点。

from __future__ import annotations

from collections import UserList
from abc import abstractmethod

from typing import (
    Sequence,
    TypeVar,
    Generic, 
    Optional,
    Union,
    Any, 
    Iterable,
    overload,
    cast
)


### ABSTRACT CLASSES ###

# Initial type
I = TypeVar('I')

# Transformed type
T = TypeVar('T') 

# Return type for methods that return self
C = TypeVar('C', bound="AbstractListPairItem[Any, Any]")


class AbstractListPairItem(UserList[I], Generic[I, T]):
    """Base class for AbstractListPairParent  and AbstractListPairChild"""
    
    __slots__ = '_other_list'
    _other_list: AbstractListPairItem[T, I]

    # UserList inherits from `collections.abc.MutableSequence`,
    # which has `abc.ABCMeta` as its metaclass,
    # so the @abstractmethod decorator works fine.
    @abstractmethod
    def __init__(self, initlist: Optional[Iterable[I]] = None) -> None:
        # We inherit from UserList, which stores the sequence as a `list`
        # in a `data` instance attribute
        super().__init__(initlist)
    
    @staticmethod
    @abstractmethod
    def transform(value: I) -> T: ...
    
    @overload
    def __setitem__(self, index: int, value: I) -> None: ...
    
    @overload
    def __setitem__(self, index: slice, value: Iterable[I]) -> None: ...
    
    def __setitem__(
        self, 
        index: Union[int, slice], 
        value: Union[I, Iterable[I]]
    ) -> None:
        
        super().__setitem__(index, value)  # type: ignore[index, assignment]
        
        if isinstance(index, int):
            value = cast(I, value)
            self._other_list.data[index] = self.transform(value)
        elif isinstance(index, slice):
            value = cast(Iterable[I], value)
            for i, val in zip(range(index.start, index.stop, index.step), value):
                self._other_list.data[i] = self.transform(val)
        else:
            raise NotImplementedError
        
    # __getitem__ doesn't need to be altered
        
    def __delitem__(self, index: Union[int, slice]) -> None:
        super().__delitem__(index)
        del self._other_list.data[index]
    
    def __add__(self, other: Iterable[I]) -> list[I]:  # type: ignore[override]
        # Return a normal list rather than an instance of this class
        return self.data + list(other)
        
    def __radd__(self, other: Iterable[I]) -> list[I]:
        # Return a normal list rather than an instance of this class 
        return list(other) + self.data
        
    def __iadd__(self: C, other: Union[C, Iterable[I]]) -> C:
        if isinstance(other, type(self)):
            self.data += other.data
            self._other_list.data += other._other_list.data
        else:
            new = list(other)
            self.data += new
            self._other_list.data += [self.transform(x) for x in new]
        return self 
    
    def __mul__(self, n: int) -> list[I]:  # type: ignore[override]
        # Return a normal list rather than an instance of this class
        return self.data * n

    __rmul__ = __mul__
    
    def __imul__(self: C, n: int) -> C:
        self.data *= n
        self._other_list.data *= n
        return self 
        
    def append(self, item: I) -> None:
        super().append(item)
        self._other_list.data.append(self.transform(item))

    def insert(self, i: int, item: I) -> None:
        super().insert(i, item)
        self._other_list.data.insert(i, self.transform(item))

    def pop(self, i: int = -1) -> I:
        del self._other_list.data[i]
        return self.data.pop(i)

    def remove(self, item: I) -> None:
        i = self.data.index(item)
        del self.data[i]
        del self._other_list.data[i]

    def clear(self) -> None:
        super().clear()
        self._other_list.data.clear()
        
    def copy(self) -> list[I]:  # type: ignore[override]
        # Return a copy of the underlying data, NOT a new instance of this class
        return self.data.copy()
        
    def reverse(self) -> None:
        super().reverse()
        self._other_list.reverse()

    def sort(self, /, *args: Any, **kwds: Any) -> None:
        super().sort(*args, **kwds)
        for i, elem in enumerate(self):
            self._other_list.data[i] = self.transform(elem)

    def extend(self: C, other: Union[C, Iterable[I]]) -> None:
        self.__iadd__(other)


# Initial type for the parent, transformed type for the child.
X = TypeVar('X')

# Transformed type for the parent, initial type for  the child.
Y = TypeVar('Y')

# Return type for methods returning self
P = TypeVar('P', bound='AbstractListPairParent[Any, Any]')



class AbstractListPairParent(AbstractListPairItem[X, Y]):
    __slots__: Sequence[str] = tuple()
    
    child_cls: type[AbstractListPairChild[Y, X]] = NotImplemented
    
    def __new__(cls: type[P], initlist: Optional[Iterable[X]] = None) -> P:
        if not hasattr(cls, 'child_cls'): 
            raise NotImplementedError(
                "'ListPairParent' subclasses must have a 'child_cls' attribute"
                )
        return super().__new__(cls)  # type: ignore[no-any-return]
    
    def __init__(self, initlist: Optional[Iterable[X]] = None) -> None:
        super().__init__(initlist)
        self._other_list = self.child_cls(
            self, 
            [self.transform(x) for x in self.data]
        )



class AbstractListPairChild(AbstractListPairItem[Y, X]):
    __slots__: Sequence[str] = tuple()
    
    def __init__(
        self, 
        parent: AbstractListPairParent[X, Y], 
        initlist: Optional[Iterable[Y]] = None
    ) -> None:
        
        super().__init__(initlist)
        self._other_list = parent
        


### CONCRETE IMPLEMENTATION ###
        

# Return type for methods returning self 
L = TypeVar('L', bound='ListKeepingTrackOfSquares')


# We have to define the child before we define the parent,
# since the parent creates the child
class SquaresList(AbstractListPairChild[int, int]):
    __slots__: Sequence[str] = tuple()
    
    _other_list: ListKeepingTrackOfSquares
    
    @staticmethod
    def transform(value: int) -> int:
        return int(pow(value, 0.5))

    @property
    def sqrt(self) -> ListKeepingTrackOfSquares:
        return self._other_list


class ListKeepingTrackOfSquares(AbstractListPairParent[int, int]):
    __slots__: Sequence[str] = tuple()
    
    _other_list: SquaresList
    child_cls = SquaresList
    
    @classmethod
    def from_squares(cls: type[L], child_list: Iterable[int]) -> L:
        return cls([cls.child_cls.transform(x) for x in child_list])
    
    @staticmethod
    def transform(value: int) -> int:
        return value ** 2
        
    @property
    def squared(self) -> SquaresList:
        return self._other_list



class SomeClass:
    def __init__(self, n: int) -> None:
        self.list = range(0, n)  # type: ignore[assignment]

    @property
    def list(self) -> ListKeepingTrackOfSquares:
        return self._list
        
    @list.setter
    def list(self, val: Iterable[int]) -> None:
        self._list = ListKeepingTrackOfSquares(val)

    @property
    def listsquare(self) -> SquaresList:
        return self.list.squared
        
    @listsquare.setter
    def listsquare(self, val: Iterable[int]) -> None:
        self.list = ListKeepingTrackOfSquares.from_squares(val)


s = SomeClass(10)

【讨论】:

  • 谢谢亚历克斯!它看起来有些复杂,我想我会通过调用 setter 来坚持显式更新,但很高兴看到它是如何实现的。
猜你喜欢
  • 1970-01-01
  • 2015-02-18
  • 2014-05-27
  • 1970-01-01
  • 2016-09-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多