This is what it does: The content of the first instance of the class ( in this case mok1 ) gets filled with water. I can fill it infinitely but as soon as the first instance is created, I can only fill that instance and generate a error by any other instance. Is there a cleaner and better way to do this? Now I use the difference in the class's var and the instance's var which is confusing for people because it are different variables. Thnx guys;)
class mok:
_content = 'EMPTY'
def __init__( self flavour ):
self.flavour = flavour
def fill( self ):
if mok._content == 'EMPTY':
self._content = '1'
mok._content = 1
if self._content == '1':
print 'Filling mok!'
else:
print 'Error: This is a different mok!'
mok1 = mok( 'thea' )
mok2 = mok( 'coffee' )
mok1.fill()
mok1.fill()
mok2.fill()
mok1.fill()
output:
Filling mok!
Filling mok!
Error: This is a different mok!
Filling mok!
I've found the solution:
class mok:
_mok_with_water = 0
def __init__( self, color, flavour ):
self.color = color
self.flavour = flavour
def printcolor( self ):
print 'Mok color =', self.color
print 'Mok flavour =', self.flavour
def fill( self ):
self.printcolor()
if mok._mok_with_water == 0:
mok._mok_with_water = self
if mok._mok_with_water == self:
print 'Filling mok!'
else:
print 'Error: This is a different mok!'
def empty( self ):
if self == mok._mok_with_water:
mok._mok_with_water = 0
mok1 = mok( 'geel', 'thee' )
mok2 = mok( 'zwart', 'koffie' )
mok1.fill()
mok1.fill()
mok2.fill()
obj = mok1.empty()
obj = mok2.fill()
obj = mok1.fill()