Classes and Objects in Python
A Python dictionary works like this
>>> d = {'a': 1, 'b': 2, 'c': 88} >>> d {'a': 1, 'c': 88, 'b': 2} >>> d['a'] 1 >>> d['c'] 88 >>>A Python module
fruit.pyworks like this:def shout(fruit): print('I LOVE ' + fruit.upper() + '!!!') favourite = 'pomegranites'
Then
>>> import fruit >>> fruit.shout('bananas') I LOVE BANANAS!!! >>> fruit.shout('apples') I LOVE APPLES!!! >>> fruit.favourite 'pomegranites' >>> fruit.shout(fruit.favourite) I LOVE POMEGRANITES!!!
Like a module, a Python
classcontains definitions and variablesclass Fruit: def __init__(self, fav): self.favourite = fav def shout(self, fruit): print("I LOVE " + fruit.upper() + "!!!") def shoutd(self, fruit=None): if not fruit: fruit = self.favourite print("I LOVE " + fruit.upper() + "!!!")
Then
>>> import fruit_class >>> f = fruit_class.Fruit('mango') >>> f.shout('apple') I LOVE APPLE!!! >>> f.shout() Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: shout() takes exactly 2 arguments (1 given) >>> f.shoutd('pear') I LOVE PEAR!!! >>> f.shoutd() I LOVE MANGO!!!
Note how
selfrefers to the object itself and how you need to passselfto each method of the class.Classes can inherit behaviour from each other
class Generalist: def __init__(self, param): print("Generalist:", param) def method(self, param): print("Generalist.method:", param) def othermethod(self, param): print("Generalist.othermethod:", param) class Specialist(Generalist): def __init__(self, param): super(Specialist, self).__init__(param) print("Specialist:", param) def method(self, param): Generalist.method(self, param) print("Specialist.method:", param)
then
>>> g = Generalist('jack') Generalist: jack >>> s = Specialist('jill') Generalist: jill Specialist: jill >>> g.method('a') Generalist.method: a >>> g.othermethod('a') Generalist.othermethod: a >>> s.method('a') Generalist.method: a Specialist.method: a >>> s.othermethod('a') Generalist.othermethod: a >>>
Here is a more useful Python class. It's for a queue
class Queue: def __init__(self): self.items = [] def isEmpty(self): return self.items == [] def enqueue(self, item): self.items.insert(0,item) def dequeue(self): return self.items.pop() def size(self): return len(self.items)
The
Queueclass can be used like this:q = Queue() q.enqueue('cat') q.enqueue('dog') q.enqueue(3) q.enqueue(4) print(q.dequeue()) print(q.dequeue()) print(q.dequeue()) del q
- This is object-oriented programming which encompasses some or all of the notions of encapsulation, data hiding, inheritance and classes. Note that Python does not enforce data hiding.