简体   繁体   中英

Python - Method to operate on a class attribute, where the attribute is dynamically specified in a class method

Apologize if this is duplicate - not sure how to word what I"m trying to accomplish.

I have two class' of interest here (in brief):

class Patient:
    ...
    self.weight = (some float)
    self.medicationDays = (some float)
    self.AverageWeightChange = (some float)
    etc.

class PtAnalyzer:
    ...
    self.ptList1 = [listOfPatients]
    self.ptList2 = [anotherListOfPatients]

    def getSummaryStats(self,ptList,metric):
        list = [patient.metric for patient in ptList]
        self.getStats(list)
        return list

    def sendForStats(self):
        weightStats = self.getSummaryStats(self.ptList1, metric = weight)
        avgWeightStats = self.getSummaryStats(self.ptList1, metric = AverageWtChange)
        ...

So the program gathers a bunch of patient instances, then passes them off to the PtAnalyzer which has an attribute - a list holding the Patient instances. Since most of the patient Metrics I"m analyzing are simple floats, I can run stats on them in a standard fashion, though I need to convert the metrics to a list first (for the stats function).

My Question: How can I tell the getSummaryStats function which metric to use? I'm trying to not write separate functions for each metric - seems non-parsimonious.

(This is actually run in a Jython 2.5.2 environment as it needs JDBC, though I use no other Jython spec. functionality)

You want getattr() ; pass the metric to use as a string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM