waltermilner

Untitled

Aug 11th, 2013
219
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.74 KB | None | 0 0
  1. # Can we write a function which behaves as a class?
  2.  
  3. def FuncAsClass():
  4.     x=1             # data members
  5.     def setX(val):  # setter methods
  6.         nonlocal x
  7.         x=val
  8.     def getX():     #getter
  9.         return(x)
  10.     def adder():    # arbitrary state-dependent method
  11.         total=0
  12.         for i in range(x+1):
  13.             total+=i
  14.         return total
  15.     # the interface offered by the class
  16.     interface ={"setX":setX, "getX":getX, "sum":adder }
  17.     return interface
  18.  
  19.  
  20. object1=FuncAsClass()
  21. object2=FuncAsClass()
  22. object1["setX"](3)
  23. object2["setX"](4)
  24. print(object1["getX"]())
  25. print(object2["getX"]())
  26. print(object1["sum"]())
  27. # data members are always private
  28. # print(Func.x) no such thing
  29. # print(f1.x) no such thing
Advertisement
Add Comment
Please, Sign In to add comment