Advertisement
Guest User

Untitled

a guest
Aug 17th, 2017
47
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.21 KB | None | 0 0
  1. def applykwargs(kwargs,key,classobject):
  2.         """kwargs is a dictionary of the form: {'arg1':val1,....}
  3.        key is a string for the desired key to (potentially) find in kwargs, and update in classobject"""
  4.  
  5.         try:
  6.                 kwargsvalue = kwargs[key] # if key exists in kwargs, kwargsvalue will be set to it
  7.                 setattr(classobject,key,kwargsvalue) # set the appropriate value in classobject
  8.         except:
  9.                 # key does not exist in kwargs
  10.                 pass
  11.  
  12. # For you though, looping is better
  13. # say you call thisFunction(linear=True,title="awesomeness")
  14. # and you make your class have:
  15. # to set all your vars, you want to do...well first of all, from the function call, we have
  16. kwargs={'linear' : True, 'title' : "awesomeness"}
  17. # so do this:
  18.  
  19. class myClass:
  20.         linear = False
  21.         title = ''
  22.         legLoc = 2
  23.  
  24. for key, value in kwargs.iteritems(): #the iteritems let's you pick each entry one at a time, setting both the key and value
  25.         # Set correct var in your class
  26.         setattr(myClass,key,value)
  27. # That's it! Now...
  28.  
  29. print myClass.linear # will be True
  30. print myClass.title # will be "awesomeness"
  31. print myClass.legLoc # will *still* be 2
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement