Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Can we write a function which behaves as a class?
- def FuncAsClass():
- x=1 # data members
- def setX(val): # setter methods
- nonlocal x
- x=val
- def getX(): #getter
- return(x)
- def adder(): # arbitrary state-dependent method
- total=0
- for i in range(x+1):
- total+=i
- return total
- # the interface offered by the class
- interface ={"setX":setX, "getX":getX, "sum":adder }
- return interface
- object1=FuncAsClass()
- object2=FuncAsClass()
- object1["setX"](3)
- object2["setX"](4)
- print(object1["getX"]())
- print(object2["getX"]())
- print(object1["sum"]())
- # data members are always private
- # print(Func.x) no such thing
- # print(f1.x) no such thing
Advertisement
Add Comment
Please, Sign In to add comment