我应该如何处理与getter/setter相关的Python列表属性?
据我所知,Pythonic方法的一个方面是使用类的直接成员变量访问,直到需要“getter/setter”。有关代码,请访问我应该如何处理与getter/setter相关的Python列表属性?,python,list,python-3.x,properties,Python,List,Python 3.x,Properties,据我所知,Pythonic方法的一个方面是使用类的直接成员变量访问,直到需要“getter/setter”。有关代码,请访问 由于@property decorator方法,对成员变量age的访问将来可以“转换”为“getter/setter”接口,而无需重写将其设置为42的行。但是我把you添加到我的friends列表的最后一行呢Person类是否可以拦截append()调用并执行其他操作?也许将来我会决定添加一个功能,您将得到通知,他们已被添加到我的好友列表中。当然,一旦我问了这个问题,我的
由于@property decorator方法,对成员变量
age
的访问将来可以“转换”为“getter/setter”接口,而无需重写将其设置为42的行。但是我把you
添加到我的friends
列表的最后一行呢Person类是否可以拦截append()
调用并执行其他操作?也许将来我会决定添加一个功能,您将得到通知,他们已被添加到我的好友列表中。当然,一旦我问了这个问题,我的大脑就会启动并想出一个解决方案。让我知道这是好是坏。创建一个类PersonFriendList(List)
并使用所需的功能覆盖append()
,而不是在Person
中拦截.append()
调用。然后,不要将[]
分配给self.friends
分配PersonFriendList()
。.friend
值可能也应该被修饰为@属性
,以便人员
可以拦截分配,以避免.friend
写入错误类型的列表
代码在上提供
你不能“拦截”me.friends.append(你)
,而Person.friends
是一个普通的list
,但你可以提供一个方法:def append\u friend(self,friend):
@jornsharpe我想你的“普通列表”引用可能会让我意识到我需要创建一个额外的类,所以谢谢你播种我的思想。
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)
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)