python - 我应该如何处理与 getter/setter 相关的 Python 列表属性?

标签 python list python-3.x properties

据我了解,Pythonic 方式的一方面是使用类的直接成员变量访问,直到需要“getters/setters”为止。代码可在Ideone获取

class Person():
    def __init__(self, name, age=None, friends=None):
        self.name = name
        self.age = age
        if friends is None:
            self.friends = []
        else:
            self.friends = friends

me = Person('Mr. Me')
you = Person('Ms. You')

me.age = 42
me.friends.append(you)

由于 @property 装饰器方法可以访问成员变量 age将来可以“转换”为“getter/setter”接口(interface),而无需重写将其设置为 42 的行。但是我添加 you 的最后一行又如何呢?给我的friends列表? Person有可能吗?类拦截 append()调用并执行其他操作?也许将来我会决定添加 you 的功能会收到通知,它们已被添加到 mefriends列表。

最佳答案

当然,一旦我提出问题,我的大脑就会启动并想出解决方案。让我知道这是否好。不要拦截 Person 中的 .append() 调用,而是创建一个类 PersonFriendList(List) 并重写 append() 具有所需的功能。然后,不要将 [] 分配给 self.friends,而是分配 PersonFriendList().friend 值可能也应该被修饰为 @property,以便可以被 Person 拦截赋值以避免 .friend 被写入错误类型的列表。

代码可在Ideone上获取.

class Person():
    def __init__(self, name, age=None, friends=None):
        self.name = name
        self.age = age
        if friends is None:
            friends = []
        self.friends = PersonFriendList(friends)


class PersonFriendList(list):
    def __init__(self, *args):
        super(PersonFriendList, self).__init__(*args)
        self.DebugPrint('constructed with {}'.format(str(*args)))

    def DebugPrint(self, string):
        print('{}(): {}'.format(self.__class__.__name__, string))

    def append(self, *args):
        super(PersonFriendList, self).append(*args)
        self.DebugPrint('appending {}'.format(str(*args)))

me = Person('Mr. Me')
you = Person('Ms. You')

me.age = 42
me.friends.append(you)

关于python - 我应该如何处理与 getter/setter 相关的 Python 列表属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22895467/

相关文章:

python - 为什么函数cv2.HoughLinesP()有不同的效果?

python - 从另一个 Python 脚本运行 Python 脚本,传入参数

python - 如何使用 matplotlib.pyplot 将不同的函数应用于同一个绘图?

arrays - 为什么我不能在 .each 方法之外修改数组?

java - 以奇怪的方式遍历 LinkedList?

python - 使用后关闭 session

python - QtQuickControls 2.0 与 PyQt5

python - 在 python 2.7 中删除之前和包括 _ 的字符

c# - 协变地交换列表中的两个元素

python - 从数据框中删除 bool 行