Python Forum
Class object instance. Link instance attribute to class. Can it be done easier.
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Class object instance. Link instance attribute to class. Can it be done easier.
#6
@Gribouillis. I would but Point is just an example. I would have to do that for every method that could change it value.
class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y
    
    def set(self, x, y):
        self.x = x
        self.y = y
        
    def move(self, x, y):
        self.x += x
        self.y += y
        
    # some other properties
Figure out how to do it with __setattr__ and __getattr__.
class LinkObject:
    def __init__(self, value, callback):
        self.read_value = value
        self.callback = callback

    def __call__(self, value=None):
        if value is None:
            return self.read_value
        self.read_value = value
        self.callback()

    def __setattr__(self, instance, value):
        if instance in ['read_value', 'callback']:
            super().__setattr__(instance, value)
        else:
            setattr(self.read_value, instance, value)
            self.callback()

    def __getattr__(self, instance):
        return getattr(self.read_value, instance)

    def clear(self):
        self.read_value = None
        self.callback = callback
Edit. Fix __call__
99 percent of computer problems exists between chair and keyboard.
Reply


Messages In This Thread
RE: Class object instance. Link instance attribute to class. Can it be done easier. - by Windspar - Dec-03-2018, 04:23 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  [split] Class and methods ebn852_pan 9 462 May-20-2024, 08:46 PM
Last Post: ebn852_pan
  [SOLVED] [listbox] Feed it with dict passed to class? Winfried 3 258 May-13-2024, 05:57 AM
Last Post: Larz60+
  Class and methods Saida2024 2 264 May-13-2024, 04:04 AM
Last Post: deanhystad
  How does this code create a class? Pedroski55 6 633 Apr-21-2024, 06:15 AM
Last Post: Gribouillis
  class definition and problem with a method HerrAyas 2 334 Apr-01-2024, 03:34 PM
Last Post: HerrAyas
  Printing out incidence values for Class Object SquderDragon 3 384 Apr-01-2024, 07:52 AM
Last Post: SquderDragon
  class and runtime akbarza 4 481 Mar-16-2024, 01:32 PM
Last Post: deanhystad
  Operation result class SirDonkey 6 642 Feb-25-2024, 10:53 AM
Last Post: Gribouillis
  The function of double underscore back and front in a class function name? Pedroski55 9 822 Feb-19-2024, 03:51 PM
Last Post: deanhystad
  super() and order of running method in class inheritance akbarza 7 862 Feb-04-2024, 09:35 AM
Last Post: Gribouillis

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020