Reputation: 161
I've been learning about classes and how to do "object-oriented" programming in python. However, I am still having difficulties understanding some of the concepts behind classes and methods. I know that classes act as a template to create an "object", but what exactly does this template do? What is the "self" parameter that is used? For example, I am confused as to what the following code does that can't be done without classes:
class Money:
def __init__ (self, v =0):
self.value = v
def getValue (self):
return self.value
class Wallet:
def __init__ (self, b = 0):
self.balance = b
def addMoney (self, c):
self.balance += c.value
def getTotal(self):
return self.balance
c1 = Money(50)
c2 = Money(100)
c3 = Money(5)
c4 = Money(20)
p = Wallet()
p.addMoney(c1)
p.addMoney(c2)
p.addMoney(c3)
p.addMoney(c4)
print(p.getTotal())
Wouldn't this be as easily achieved with some simple raw_input()
function(s) that asks for c1, c2, c3, c4, etc and a function that adds the money together and returns it? Wouldn't that be possibly a way of doing the same thing that this class does, but with less lines of code, and the lack of a need of writing 5 methods to simply add up some numbers.
Upvotes: 1
Views: 392
Reputation: 199
Firstly, 'self' is a reference to the class instance which calls the method. Behind the scenes, Python translates
print(p.getTotal())
to
Wallet.getTotal(p)
Now for the OOP part of your question. You should always write code that would be easier to maintain down the road. OOP is just one way to make code manageable/maintainable. In small programs like the one you are talking about code maintainability doesn't become an issue and using OOP would be an overkill. Once your code size starts to grow (like 100,000 lines of code) you need to employ strategies to keep your code maintainable. The strategies generally are (the list is not complete, just for example):
At the end, it boils down to the judgement of the programmer to use that programming paradigm which makes him/her most productive while keeping good code quality.
Upvotes: 1
Reputation: 1
Yes it would be simpler to just have a function that adds the money together, but this script is just to demonstrate the ability of object-oriented programming in python. Also to improve on this script, yes you could add in a simple raw_input() to get the amounts. Also the self parameter is used to give a certain "object" a variable belonging to it's self, aka a local variable.
Upvotes: 0
Reputation: 2776
What a beautiful straw-man argument you have created! You are criticising Object Oriented Programming using a trivial example.
OOP is a way to organize code that will be useful for larger programs.
There are many complex structures you can represented with objects that are now part of the daily programming speak (Patterns). In http://www.oodesign.com/ you can see several.
I recommend you really learn and try to use OOP for a year and then just use it where it makes sense to you.
Upvotes: 1