How should I handle Python list properties with respect to getters/setters? -


it understanding 1 aspect of pythonic way use direct member variable access of classes until 'getters/setters' needed. code available on ideone

class person():     def __init__(self, name, age=none, friends=none):         self.name = name         self.age = age         if friends none:             self.friends = []         else:             self.friends = friends  me = person('mr. me') = person('ms. you')  me.age = 42 me.friends.append(you) 

because of @property decorator approach access member variable age can 'converted' 'getter/setter' interface in future without rewriting line sets 42. last line add you friends list? is possible person class intercept append() call , take other actions? perhaps in future decide add feature you notified have been added me's friends list.

of course, once ask question brain turns on , comes solution. let me know if or not. instead of intercepting .append() call in person, create class personfriendlist(list) , override append() desired functionality. then, instead of assigning [] self.friends assign personfriendlist(). .friend value should decorated @property assignment can intercepted person avoid .friend being written wrong kind of list.

code available on ideone.

class person():     def __init__(self, name, age=none, friends=none):         self.name = name         self.age = age         if friends none:             friends = []         self.friends = personfriendlist(friends)   class personfriendlist(list):     def __init__(self, *args):         super(personfriendlist, self).__init__(*args)         self.debugprint('constructed {}'.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') = person('ms. you')  me.age = 42 me.friends.append(you) 

Comments

Popular posts from this blog

PHPMotion implementation - URL based videos (Hosted on separate location) -

javascript - Using Windows Media Player as video fallback for video tag -

c# - Unity IoC Lifetime per HttpRequest for UserStore -