Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there a way to pass variable itself(not the value) as argument in Python?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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):
            ...
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading