Advertisement
furas

getattr()

Apr 27th, 2017
164
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.09 KB | None | 0 0
  1. class Celsius:
  2.     def __init__(self, temperature = 0):
  3.         self.temperature = temperature
  4.  
  5.     def to_fahrenheit(self):
  6.         return (self.temperature * 1.8) + 32
  7.  
  8.     def get_temperature(self):
  9.         print("Getting value")
  10.         return self._temperature
  11.  
  12.     def set_temperature(self, value):
  13.         if value < -273:
  14.             raise ValueError("Temperature below -273 is not possible")
  15.         print("Setting value")
  16.         self._temperature = value
  17.  
  18.     temperature = property(get_temperature,set_temperature)
  19.  
  20. # --------------------------------------
  21.    
  22. def working(aclass, method_name, set_value):
  23.     amount = aclass()
  24.     amount.temperature = set_value
  25.    
  26.     # get access to method using its name as string
  27.     method = getattr(amount, method_name)
  28.    
  29.     # execute method
  30.     print(method())
  31.  
  32. # send method name as string
  33. working(Celsius, 'to_fahrenheit', 373)
  34.  
  35. # --------------------------------------
  36.  
  37. def working2(obj, method, set_value):
  38.     obj.temperature = set_value
  39.     print(method())
  40.  
  41. c = Celsius()
  42. working2(c, c.to_fahrenheit, 373)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement