python - Using Class method to add a Class variable -


the following code adds 2 pretty tables mytableclass. tables initiated in class constructor. create 2 class methods addtable , addtablerow adding additional tables , data rows specifying newtable name. syntax need this? wrote code in class methods place holder.

from prettytable import *  class mytableclass(object):      def __init__(self):         self.table1 =prettytable(["student name", "score test 1"])         self.table2=prettytable(["student name", "score test 2"])      def addtable (self, newtable, **kwargs):         #what syntax make newtable class variable of mytableclass?         self.newtable = prettytable(kwargs.values())      def addtablerow(self, newtable, **kwargs):         #what syntax use newtable add data added table?         self.newtable.add_row(kwargs.values())   def main():     m = mytableclass()     m.table1.add_row(["kenny", 86])     m.table1.add_row(["jackson", 72])     m.table1.add_row(["charlie", 100])     m.table2.add_row(["kenny", 95])     m.table2.add_row(['jackson', 85])     m.table2.add_row(["charlie", 99])   print (m.table1) print (m.table2)  if __name__ == "__main__":     main() 

you can use setattr function set attribute:

def addtable (self, newtable, **kwargs):     setattr(self, newtable, prettytable(kwargs.values())) 

and can use getattr obtain attribute name:

def addtablerow(self, newtable, **kwargs):     getattr(self, newtable).add_row(kwargs.values()) 

however simpler use dictionary of tables:

class mytableclass(object):      def __init__(self):         self.tables = {             'table1': prettytable(["student name", "score test 1"]),             'table2': prettytable(["student name", "score test 2"]),         }      def addtable (self, newtable, **kwargs):         self.tables[newtable] = prettytable(kwargs.values())      def addtablerow(self, newtable, **kwargs):         self.tables[newtable].add_row(kwargs.values()) 

if want able access given table via attribute, self.table1 in examples, define __getattr__ as:

def __getattr__(self, name):     return self.tables[name] 

Comments

Popular posts from this blog

java - WrongTypeOfReturnValue exception thrown when unit testing using mockito -

php - Magento - Deleted Base url key -

android - How to disable Button if EditText is empty ? -