Friday, November 11, 2011

[Level 2] classmethod, staticmethod, abstractmethod decorators in Python.

#!/bin/env python
from abc import *

class p(object):
    __metaclass__ = ABCMeta

    @abstractmethod
    def printz(self):
        pass

    @abstractproperty
    def x(self):
        pass

class o(p):
    def __init__(self, n=10):
        self._x = n 

    def printX(self):
        print self._x

    def printx(self):
        print self.x

    @classmethod
    def printy(self):
        print self.x

    @staticmethod
    def printz():
        print 'x' 

    @property
    def x(self):
        return self._x

    @x.setter
    def x(self, times):
        self._x = self._x * times

    @x.getter
    def x(self):
        return self._x

a = o(2)
a.x = 5
print a.x
a.printX()
a.printx()
a.printy()
a.printz()

#o.printX() # error
#o.printx() # error
o.printy()
o.printz()

$ ./t.py 
10
10
10
<property object at 0x177a1b0>
x
<property object at 0x177a1b0>
x

Wish this helps.
regards,
Stanley Huang