I have a class with several data member and I want to write a function to compare different data member depend on the input of that function. Is there a way to pass variable itself into the function?
For example:
class someClass:
self.a = 1
self.b = 1.1
self.c = 1
def someFunction(x, lt, var): #lt is a list of someClass, var is the variable I want to choose to compare with
for v in lt:
if x.var < v.var:
...
I think there must be some distinct characteristic between same variable in deferent instance, but not sure what it is.
Thank you!
>Solution :
Yes, but it’s probably not what you want.
If you find yourself accessing things by (string) names a lot, you’re looking for a dictionary. Rather than having three separate fields self.a, self.b, and self.c, consider having just one: self.data.
class SomeClass:
def __init__(self):
self.data = {
"a": 1,
"b": 1.1,
"c": 1,
}
def some_function(x, some_class_instances, var):
for y in some_class_instances:
if x.data[var] < y.data[var]:
...
Generally, you want to use dictionaries if you want this form of access.
That being said, what you asked for can be done. Pretty much anything can be done in Python, with enough effort. To be clear, I strongly recommend using a dictionary, but for completeness, getattr is a built-in Python function that performs dot-notation style access with a string argument. This won’t just get slots on __dict__; it’ll also catch propertys, other descriptors, or anything else; it’s literally equivalent to using a dot to access the field, with all the caveats that come with that.
def some_function(x, some_class_instances, var):
for y in some_class_instances:
if getattr(x, var) < getattr(y, var):
...