Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Intercepting changes of attributes in classes within a class - Python

I have been messing around with pygame and python and I want to be able to call a function when an attribute of my class has changed. My current solution being:

class ExampleClass(parentClass):
   def __init__(self):
      self.rect = pygame.rect.Rect(0,0,100,100)
   def __setattr__(self, name, value):
      parentClass.__setattr__(self,name,value)
      dofancystuff()
Firstclass = ExampleClass()

This works fine and dofancystuff is called when I change the rect value with Firsclass.rect = pygame.rect.Rect(0,0,100,100). However if I say Firstclass.rect.bottom = 3. __setattr__ and there for dofancystuff is not called.

So my question I guess is how can I intercept any change to an attribute of a subclass?

edit: Also If I am going about this the wrong way please do tell I'm not very knowledgable when it comes to python.

like image 406
tomeedee Avatar asked Mar 05 '26 06:03

tomeedee


2 Answers

Well, the simple answer is you can't. In the case of Firstclass.rect = <...> your __setattr__ is called. But in the case of Firstclass.rect.bottom = 3 the __setattr__ method of the Rect instance is called. The only solution I see, is to create a derived class of pygame.rect.Rect where you overwrite the __setattr__ method. You can also monkey patch the Rect class, but this is discouraged for good reasons.

like image 164
Oliver Andrich Avatar answered Mar 07 '26 23:03

Oliver Andrich


You could try __getattr__, which should be called on Firstclass.rect.

But do this instead: Create a separate class (subclass of pygame.rect?) for ExampleClass.rect. Implement __setattr__ in that class. Now you will be told about anything that gets set in your rect member for ExampleClass. You can still implement __setattr__ in ExampleClass (and should), only now make sure you instantiate a version of your own rect class...

BTW: Don't call your objects Firstclass, as then it looks like a class as opposed to an object...

like image 23
Daren Thomas Avatar answered Mar 07 '26 22:03

Daren Thomas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!