L
L
lleballex2020-07-12 08:37:01
Python
lleballex, 2020-07-12 08:37:01

What is the correct way to implement __setattr__ or overload comparison operator in Python?

I have two classes: Field and Object . The field contains the variable "value" and much more. An instance of the first class is created in the Object . And I need that when I assign a value to this variable ( field ) it is assigned to the field.value variable (I write obj.field = 1, but obj.field.value = 1 worked)

I can write the __setattr__ function in the Object . But then how to make the assignment work as usual for other variables of this class? Or maybe you can somehow overload the assignment operator in the Field class ?

class Field:
    value = None

class Obj:
    field = Field()
    def __setattr__(self, name, field):
        ...

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dr. Bacon, 2020-07-12
@lleballex

Ramalho Luciano "Fluent Python", Chapter 20, Attribute Descriptors, but it's too early for beginners.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question