据我了解,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
的功能会收到通知,它们已被添加到 me
的friends
列表。
最佳答案
当然,一旦我提出问题,我的大脑就会启动并想出解决方案。让我知道这是否好。不要拦截 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/