Capturing attribute changes in classes inside a class - Python

I talked with pygame and python, and I want to be able to call a function when the attribute of my class has changed. My current solution:

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 so Firstclass.rect.bottom = 3. __setattr__and there for dofancystuff is not called.

So my question is, I think, how can I intercept any change in the attribute of a subclass?

edit: Also, if I am going to do it wrong, please say that I am not very knowledgeable when it comes to python.

+3
source share
4 answers

, - . Firstclass.rect = <...> __setattr__. Firstclass.rect.bottom = 3 __setattr__ Rect. , , - pygame.rect.Rect, __setattr__. Rect, .

+4

__getattr__, Firstclass.rect.

: ( pygame.rect?) ExampleClass.rect. __setattr__ . , rect ExampleClass. __setattr__ ExampleClass ( ), , rect...

BTW: Firstclass, , ...

+1

, :

self.__dict__[name] = value

, ,

parentClass.__setattr__(self, name, value)

Python (setattr → http://docs.python.org/2/reference/datamodel.html?highlight=setattr#object. setattr) , , parentClass setattr.

!

+1

, , , , .

, :

myObject.attribute.thing = value

. :

anAttribute = myObject.attribute
anAttribute.thing = value

myObject, , , ; .

, , __setattr__ .

, , , __getattribute__ __getattr__, , __setattr__. , , , .

__getattribute__ __getattr__. . , , , , __getattr__, , / - , __getattr__ , __getattribute__, .

, , , , .

0

Source: https://habr.com/ru/post/1705249/


All Articles