[Tutor] lunch.py

Sean Perry shaleh at speakeasy.net
Tue Feb 7 19:27:20 CET 2006


Christopher Spears wrote:
> I'm working on a program where a Customer orders Food
> from an Employee.  Here is what I have so far:
> 
> class Food:
> 	def __init__(self, name):
> 		Food.foodName = name
> 

what you want here is 'self.name = name' then in your code later you can do:

protein = Food("hamburger")
lipid = Food("olive oil")
print protein.name
print lipid.name

> class Customer:
> 	def __init__(self,name):
> 		Customer.name = name
> 	def placeOrder(self, employee, food):
> 		print "%s, I want, %s please! " % Employee.name,
> food.foodName
> 
> class Employee:
> 	def __init__(self, name):
> 		Employee.name = name
>

same for these, use self.name.

'self' is the item you are constructing. in my example above the Food 
class is instantiated with the name 'hamburger' and assigned to protein. 
When your code assigned to Food.foodName you were making *ALL* instances 
of Food be the same food. Observe:
 >>> class Food:
...   def __init__(self, name):
...     Food.foodName = name
...
 >>> protein = Food('hamburger')
 >>> protein.foodName
'hamburger'
 >>> lipid = Food('olive oil')
 >>> lipid.foodName
'olive oil'
 >>> protein.foodName
'olive oil'

So to recap, use the class name when you want all instances to share a 
variable i.e. a count of the number of items. Use 'self' when you want 
each instance to have its own version of the variable, like your 'name'.


More information about the Tutor mailing list