In Matlab, let's consider a structure "structure" and a list of fields "list_of_fields".
structure = struct;
list_of_fields = ["a","b","d"]; % Some specific fields of the structure and not all of them
for field = list_of_field
structure.(field) = 0;
end
I would like to do the same in Python with the attribute of a class: instead of writing:
class Example
def __init__(self) :
self.a = 0
self.b = 0
self.d = 0
My goal would be to write a loop that iterates over the specific attribute a, b and d (and no other attribute). How do you achieve that in Python ?
Up to now, I accessed all attribute as in the Python example aforementioned.
As I mentioned what you are trying to do is a very bad idea imho... But if you really want it you can define
__getitem__method and return value if it's in let's say set of values of your interest and raiseStopIterationotherwise. This will allow to loop over those attributes using for loop and it won't return neither methods nor other attributes of that object.Side notes and why you should NOT do that:
dicts,dataclasses and so on__dict__is created you have to define those attributes you want to loop through in the very specific order, otherwise theStopIterationwill be raised too early and you won't get all the values you want. Which is again very bad, cause it's an implementation detail and anyone using your code doesn't have to know that, neither it's obvious from looking at your code.To see what I mean just change the order and define
Examplelike this and again see the output ofe.__dict__:The code won't work anymore with that change