Advertisement
Guest User

Untitled

a guest
Dec 26th, 2017
185
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.83 KB | None | 0 0
  1. Why use classes.
  2.  
  3. In OOP, you have functions that are wrappers for commands, at the most basic level.
  4.  
  5. Instead of having to write c = a+b; print c, you can instead do this:
  6.  
  7. def foo(a,b):
  8. return a+b
  9.  
  10. Now, as you can see, "foo" is a great way to keep two pieces of information relevant to each other in the same place. If it wasn't for the function, they wouldn't have a name, this process that can repeat itself is now a "function" (since you can use "foo" all the time, with any variables).
  11.  
  12. Now, apply the same thing of keeping relevant information together to classes.
  13.  
  14. class Tree:
  15. def __init__(self):
  16. self.branches = []
  17. def createBranches(self):
  18. self.branches = ['branch1', 'branch2']
  19. def showBranches(self):
  20. return self.branches
  21.  
  22. Imagine now we initialize the object "Tree" -> obj=Tree() and then ask it to show us its branches: obj.showBranches(), it will output 'branch1, branch2'.
  23.  
  24. What did we do? We put 2 functions in a class that had business to do with each other and allowed them to have the same memory space.
  25.  
  26. If these two functions were to be declared in different blocks, such as:
  27.  
  28.  
  29. def createBranches(self):
  30. branches = ['branch1', 'branch2']
  31. def showBranches(self):
  32. return branches
  33.  
  34. They'd have no business to do with each other and showBranches would show an error, because it cannot access "branches" variable which is a local variable only within createBranches.
  35.  
  36. As such:
  37.  
  38. Every time you have two functions that have to do with each other and need to share information and it make sense for them to be in the same place, rather than different, use a class.
  39.  
  40. For example from the real world, a HTTP connection function has nothing to do with a strip-string function, as such, define your HTTP connection function in a class and leave the strip-string function outside, they do different things.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement