Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/351.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
我应该如何处理与getter/setter相关的Python列表属性?_Python_List_Python 3.x_Properties - Fatal编程技术网

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

我应该如何处理与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()调用并执行其他操作?也许将来我会决定添加一个功能,您将得到通知,他们已被添加到我的好友列表中。当然,一旦我问了这个问题,我的

据我所知,Pythonic方法的一个方面是使用类的直接成员变量访问,直到需要“getter/setter”。有关代码,请访问


由于@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)