Object Oriented Programming With Python (part 1) - What's In A Name?
(Page 3 of 6 )
Let's now add a few properties to the mix, by modifying the class definition to support some additional characteristics:
class veryBigSnake:
# some useful methods
def eat(self):
# code goes here
def sleep(self):
# code goes here
def squeeze_to_death(self):
# code goes here
def set_snake_name(self, name):
# code goes here
self.name = name
The class definition now contains one additional method,
set_snake_name(), which modifies the value of the property "name". Let's see how this works:
>>> alpha = veryBigSnake()
>>> beta = veryBigSnake()
>>>
>>> # name the alpha snake
>>> alpha.set_snake_name("Peter Python")
>>> alpha.name
'Peter Python'
>>>
>>> # name the beta snake
>>> beta.set_snake_name("Bobby Boa")
>>> beta.name
'Bobby Boa'
>>>
>>> # rename the alpha snake
>>> alpha.set_snake_name("Sally Snake")
>>> alpha.name
'Sally Snake'
>>>
As the illustration above shows, once new objects are
defined, their individual methods and properties can be accessed and modified independent of each other. This comes in very handy, as the next few pages will show.
It's also important to note the manner in which object methods and properties are accessed - by prefixing the method or property name with the name of the specific object instance.
Next: Digging Deep >>
More Python Articles
More By icarus, (c) Melonfire