D
D
Denis Tikhonov2021-10-11 15:50:54
Python
Denis Tikhonov, 2021-10-11 15:50:54

How to make an object property the default in Python like in VBA?

Suppose I need to calculate A = B + C (operations can be arbitrary), where A, B and C are objects of the same class with many properties and methods. I want the expression above to read the values ​​from the Value property of objects B and C and calculate them into a new value that would be assigned to the Value property of object A. At the same time, other properties and methods would be accessed as usual through a dot. I need this to implement the visibility of variables of simple (basic) types in complex expressions. In VBA, this can be achieved with a special property attribute on an object derived from the class.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vindicar, 2021-10-11
@Kelleam

Magic methods will help.
This is not a "default property", but rather "defining the meaning of the operation for a given object", but the final result will be about the same.
You can also use the __int__() , __float__() , and __complex__() methods to transparently convert an object to a number. But __add__() is usually more practical.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question