Jump to content


Photo
- - - - -

Python - A Beginner's Lesson in OOP


  • Please log in to reply
No replies to this topic

#1 Leibrockoli

Leibrockoli

    Young Padawan

  • Members
  • Pip
  • 27 posts

Posted 28 May 2008 - 10:46 PM

Congratulations! By clicking on this topic, you hereby show some interest in a programming language that is making it's way up the ladder of programming languages! Claps all around!

Now, before I begin, I must introduce a short bit of Python to those who do not quite know it yet, or have even heard of it (short of knowing the actual snake of course).

Python, is, as their website would say, a very powerful object-oriented programming language that's fast and dynamic. Many people say they can learn this language faster than they could other languages, etcetera etcetera, basically, the point is - this is a language that is much easier to use. Other languages, like the C/C++/C# family, can be very confusing, or not everyone understands the capabilities of Java so easily. Henceforth, Python comes along and mixes things up just one bit more. HOWEVER! One thumb of rule before even thinking of discussing this with others - or maybe reading Python books - Monty Python jokes will be made.

For the documentation, downloads, and other assorted SPAM, go to:
http://www.python.org/

Python runs on Windows, Macintosh, and Linux/Unix systems. Learning this language shouldn't pose many problems in terms of downloading errors.

--- Short Prayer Before Using Holy Hand Grenade. ---

Now for you new beginners, Python looks like a new opportunity to try your shot at a different way for computer programming. But BE WARNED. Count three seconds before doing some of these rules:

  • Python is indent-sensitive. In order to replace brackets { }, Python uses indents.
  • Python has no special character to call variables ($, % etc.)
  • Python you don't have to tell your variable what it is. (Boolean, integer, float) Python will automatically recognize it.
  • Operators (==, !=, <=, >=, +=, -=) are still used!
  • Save your Python files as a Python file (.py, .pyw) or they won't compile in the IDLE!
  • There aren't any && or || operators in if statements. Just 'and' and 'or'

--- Now for something... completely different. ---

Now, as many as you may be wondering right at this moment, what the holy grail is OOP? OOP stands for object-oriented programming, which is a famous way of programming spread amongst almost any programming language. Object-Oriented Programming is a method that enables something called a class to be built, and within this class are several functions. Data is put into the class, and the functions roughly manipulate that data. If anyone remembers from the PHP days, OOP was written like...
<?php
					class Twohundredfoottallhedgehog{
					//class
					function Dimmsdale(){
					//function
					print "Dimmsdale...";
					}
					}
					$hedgehog = new Twohundredfoottallhedgehog;
					$hedgehog->Dimmsdale();
					?>

While in the reign of Python, it's now:

class Killersheep(object):
						def First_Class_Shot(self):
							print "He shot me!"
					
					Sheepinthewalls = Killersheep()
					Sheepinthewalls.First_Class_Shot()

As you can see, Python's OOP is not much different from any other, but is written simpler.

The question is now, what good is OOP for anyway?

Probably the most basic of OOP lessons taught that I know, is the shopping cart way. OOP is like taking items and putting them into a shopping cart, and manipulating the items within it. I teach it, in a different way - through fish licenses.

You might ask "That's ridiculous! Fish don't need licenses!" But let's take a look at an example.

class Licenses(object):
						def __init__(self): # initializing function
						   self.pet = "fish" #type of license
						   self.amnt = 6 #how many I have
					
						def buy_licenses(self,amnt):
						   self.amnt += amnt  #formula to add licenses
						   print "You bought",amnt,self.pet,"licenses."
						   print "You now have",self.amnt,self.pet,"licenses."
					
					fish = Licenses() #activating the object
					fish.buy_licenses(4) #using buy_license function

The result will outcome to:

You bought 4 fish licenses.
					You now have 10 fish licenses.

So you're going to wonder about it then. Let's break it down.

Let's say I have 6 fish licenses for my pet goldfish. I go to the license office, and I say to the guy I want to buy 4 licenses for my new fish. The queen bursts in after the guy refuses me licenses, thinking it's "silly", and I get issued 4 new licenses. So that adds to my current amount of fish licenses. We could also break it down further to different types of licenses and buying further amounts of them, but that's the amount of fun that you will have exploring python.

--- Life of a Lumberjack ---

You're probably wondering at this point, how can we make OOP a bit more fun in Python? Well, we haven't been so much as to building an active OOP script which we can play with after scripting, so I think it's time to do that right now - by building an active OOP script.

By active, I mean you can actually interact with this. Let's be lumberjacks for a day. We work all day and we sleep all night. Maybe Wednesday we can go shopping and get some buttered scones. But in the Lumberjack situation, we need to work and chop trees, sleep, sell the wood, and get some scones with the money. In a way, this poses for a good game simulation where we have variables and have to manage time/effort. Sadly, it's just text for now.

So the cycle of this would be energy -> wood -> money -> scones. Let's start by making some attributes for the class.

class Lumberjack(object):
				  def __init__(self):
					  self.energy =  100;
					  self.money = 0;
					  self.wood = 0;
					  self.scones = 0;

So far so good. We should now create some functions on gaining wood, and then selling wood for money. Later we'll create limits on the attributes so they don't go below 0 and such.

A re-usable function to display our resources:
def Currently(self):
				  print "Energy:",self.energy
				  print "Money:",self.money
				  print "Wood:",self.wood
				  print "Scones:",self.scones

Chopping wood down:
			  def Chop_Wood(self):
		  
				  print "You attempt to cut down the tree..."
				  if(self.energy > 0):
					  self.wood += 1
					  self.energy -= 10
					  print "...You cut down the tree."
					  print "You gain wood."
					  print ""
				  else:
					  print "... But you don't have enough energy to."
					  print ""
				  self.Currently()

Selling the wood for profit:
def Sell_Wood(self,amt):
				  print "You go to sell some wood..."
				  if(self.wood >= (0+amt)):
					  self.wood -= amt
					  self.money = 50*amt
					  print "...You manage to sell your wood."
					  print "You gain",amt*50,"dollars."
					  print ""
				  else:
					  print "...But you have no wood."
					  print ""
					  self.Currently()

Buying a scone (priced at 2 american dollars):
def Buy_Scone(self):
				print "You go shopping for scones..."
				if(self.money >= 2):
					self.money -= 2
					self.scones += 1
					print "...You manage to find some nice scones."
					print "You gain a scone."
					print ""
				else:
					print "...But you have no money to buy it with."
					print ""
				self.Currently()

Eating the scones:
def Eat_Scone(self):
			  print "You're hungry for a scone..."
			  if(self.scones > 0):
				  self.scones -= 1
				  self.energy += 25
				  print "...The scone fills you up."
				  print "It's nicely buttered with some tea."
				  print ""
			  else:
				  print "...But you have no scones, sadly."
				  print ""
			  self.Currently()

And finally - sleeping!
def Sleep(self):
			  print "After a long day of work, you're very tired."
			  print "You go to sleep, after skipping home..."
			  self.energy = 100
			  print "...You feel rejuvenated!"
			  print "Don't forget your high heels!"
			  print ""
			  self.Currently()

Now, here is our final outcome with all the classes.
class Lumberjack(object):
		  def __init__(self):
			  self.energy =  100;
			  self.money = 0;
			  self.wood = 0;
			  self.scones = 0;
	  
			  if(self.energy>100):
				  self.energy = 100
	  
			  if(self.money < 0):
				  self.money = 0
	  
			  if(self.energy < 0):
				  self.energy = 0
	  
			  if(self.scones < 0):
				  self.scones = 0
	  
			  if(self.wood < 0):
				  self.wood = 0
	  
			  print "Let's start lumberjacking!"
			  print ""
			  self.Currently()
	  
		  def Currently(self):
			  print "Energy:",self.energy
			  print "Money:",self.money,"$"
			  print "Wood:",self.wood
			  print "Scones:",self.scones
			  print ""
	  
		  def Chop_Wood(self):
	  
			  print "You attempt to cut down the tree..."
			  if(self.energy > 0):
				  self.wood += 1
				  self.energy -= 10
				  print "...You cut down the tree."
				  print "You gain wood."
				  print ""
			  else:
				  print "... But you don't have enough energy to."
				  print ""
			  self.Currently()
	  
		  def Sell_Wood(self):
			  print "You go to sell some wood..."
			  if(self.wood > (0)):
				  self.wood -= 1
				  self.money = 20
				  print "...You manage to sell your wood."
				  print "You gain 50$ dollars."
				  print ""
			  else:
				  print "...But you have no wood."
				  print ""
			  self.Currently()
	  
		  def Buy_Scone(self):
			  print "You go shopping for scones..."
			  if(self.money >= 2):
				  self.money -= 2
				  self.scones += 1
				  print "...You manage to find some nice scones."
				  print "You gain a scone."
				  print ""
			  else:
				  print "...But you have no money to buy it with."
				  print ""
			  self.Currently()
				  
		  def Eat_Scone(self):
			  print "You're hungry for a scone..."
			  if(self.scones > 0):
				  self.scones -= 1
				  self.energy += 25
				  print "...The scone fills you up."
				  print "It's nicely buttered with some tea."
				  print ""
			  else:
				  print "...But you have no scones, sadly."
				  print ""
			  self.Currently()
	  
		  def Sleep(self):
			  print "After a long day of work, you're very tired."
			  print "You go to sleep, after skipping home..."
			  self.energy = 100
			  print "...You feel rejuvenated!"
			  print "Don't forget your high heels!"
			  print ""
			  self.Currently()

I added in the limits at the __init__(self) stage to tell the object never to go higher or lower than certain numbers.

After that long, lengthy amount of coding, you're wondering how you can play it like a game now, right? Well, are you familiar with if statements? Let's create an ask option function to ask the user what function they want to use.

Ask_Option function
def Ask_Option(self):
			  print "a) Chop some wood"
			  print "b) Sell some wood"
			  print "c) Buy a scones"
			  print "d) Eat some scones"
			  print "e) Go home and sleep"
			  print ""
			  get_option = raw_input("What would you like to do? ").lower()
	  
			  if(get_option == "a"):
				  self.Chop_Wood()
			  elif(get_option == "b"):
				  self.Sell_Wood()
			  elif(get_option == "c"):
				  self.Buy_Scone()
			  elif(get_option == "d"):
				  self.Eat_Scone()
			  elif(get_option == "e"):
				  self.Sleep()
			  else:
				  print "Sorry, but could you sing that again?"
				  print ""
				  self.Ask_Option()

We went through all that hard work to make the Currently() repeat after those options, so glue Ask_Option to Currently() to save time.

Ask_Option glued to Currently():
def Currently(self):
			  print "Energy:",self.energy
			  print "Money:",self.money,"$"
			  print "Wood:",self.wood
			  print "Scones:",self.scones
			  print ""
			  self.Ask_Option()

Now, that finishes that whole entire script. Add this to the bottom....

Variable=Lumberjack()

...And you'll be enjoying your new simulation! Enjoy the life of a lumberjack!

This simulation is a very tedious one. There is no goal, nor does it present any way in ending. It's a repetitive simulation and it shows how OOP works in a full example. Creativity brings about your own examples in the future.

--- And now for something completely different! Again! ---

That's it for all I have to teach about OOP in Python. You can now use these techniques in your own Python examples. However, using other various Monty Python jokes I hope. Like Killer Cars, Cheese Shop, The Silly Walk Institution, Spam/Viking Diner, and the list just keeps going on...

That's all for what I have to teach now! Be sure to check out different Python styles! Python brings about a new age of computer programming!

Final code(Lumberjack.py):
class Lumberjack(object):
	def __init__(self):
		self.energy =  100;
		self.money = 0;
		self.wood = 0;
		self.scones = 0;

		if(self.energy>100):
			self.energy = 100

		if(self.money < 0):
			self.money = 0

		if(self.energy < 0):
			self.energy = 0

		if(self.scones < 0):
			self.scones = 0

		if(self.wood < 0):
			self.wood = 0

		print "Let's start lumberjacking!"
		print ""
		self.Currently()

	def Currently(self):
		print "Energy:",self.energy
		print "Money:",self.money,"$"
		print "Wood:",self.wood
		print "Scones:",self.scones
		print ""
		self.Ask_Option()

	def Ask_Option(self):
		print "a) Chop some wood"
		print "b) Sell some wood"
		print "c) Buy a scones"
		print "d) Eat some scones"
		print "e) Go home and sleep"
		print ""
		get_option = raw_input("What would you like to do? ").lower()
		print ""

		if(get_option == "a"):
			self.Chop_Wood()
		elif(get_option == "b"):
			self.Sell_Wood()
		elif(get_option == "c"):
			self.Buy_Scone()
		elif(get_option == "d"):
			self.Eat_Scone()
		elif(get_option == "e"):
			self.Sleep()
		else:
			print "Sorry, but could you sing that again?"
			print ""
			self.Ask_Option()

	def Chop_Wood(self):

		print "You attempt to cut down the tree..."
		if(self.energy > 0):
			self.wood += 1
			self.energy -= 10
			print "...You cut down the tree."
			print "You gain wood."
			print ""
		else:
			print "... But you don't have enough energy to."
			print ""
		self.Currently()

	def Sell_Wood(self):
		print "You go to sell some wood..."
		if(self.wood > (0)):
			self.wood -= 1
			self.money += 20
			print "...You manage to sell your wood."
			print "You gain 50$ dollars."
			print ""
		else:
			print "...But you have no wood."
			print ""
		self.Currently()

	def Buy_Scone(self):
		print "You go shopping for scones..."
		if(self.money >= 2):
			self.money -= 2
			self.scones += 1
			print "...You manage to find some nice scones."
			print "You gain a scone."
			print ""
		else:
			print "...But you have no money to buy it with."
			print ""
		self.Currently()
			
	def Eat_Scone(self):
		print "You're hungry for a scone..."
		if(self.scones > 0):
			self.scones -= 1
			self.energy += 25
			print "...The scone fills you up."
			print "It's nicely buttered with some tea."
			print ""
		else:
			print "...But you have no scones, sadly."
			print ""
		self.Currently()

	def Sleep(self):
		print "After a long day of work, you're very tired."
		print "You go to sleep, after skipping home..."
		self.energy = 100
		print "...You feel rejuvenated!"
		print "Don't forget your high heels!"
		print ""
		self.Currently()

		

Variable = Lumberjack()

Edited by Leibrockoli, 28 May 2008 - 10:54 PM.





0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users