Sunday, February 27, 2011

[Level 3] Python Abstract Class Implement

If you want to implement python abstract class,
you could use astract base class of python.
The sample code as the following:

[common.py]
#!/bin/env python
from abc import *
__all__ = ['CommonClass']

class CommonClass:
    __metaclass__ = ABCMeta
    def __init__(self, name, age):
        self.name = name
        self.age = age
    def displayAge(self):
        print 'My age is: %s' % self.age

    @abstractmethod
    def displayName(self):
       pass

[myABC.py]
#!/bin/env python
from common import *
class MyClass(CommonClass):
    def __init__(self, name, age):
        CommonClass.__init__(self, name, age)
   
    def displayName(self):
        print "Hi %s!" % self.name

if __name__ == "__main__":
    st = MyClass('Stanley', 25)
    st.displayAge()
    st.displayName()

execute myABC.py
# ./myABC.py
My age is: 25
Hi Stanley!
#

According to above sample,
if you want to define abstract class,
you have three things to do. (ref. red words in common.py)
1. import abstract base class.
from abc import *
2. define __metaclass__.
__metaclass__ = ABCMeta
3. use decoration of method
@abstractmethod
def method_name(self):
...


And if you want to implement it.
You need to define the abstract method. (ref. red words in myABC.py)
ex. def method_name(self):
...

If you don't define the abstract method, you might got the errormessage.
# cat ./myABC.py
...
#    def displayName(self):
#        print "Hi %s!" % self.name
...
# ./myABC.py
Traceback (most recent call last):
  File "./myABC.py", line 13, in
    st = MyClass('Stanley', 25)
TypeError: Can't instantiate abstract class MyClass with abstract methods displayName

Wish this helps.
regards,
Stanley Huang