[Level 2] Implement static/class method in Python class.

You can use @staticmethod (decorator) to implement static method in Python class.

#!/usr/bin/env python
class de:
  def __init__(self):
    self.a = 1
  def getA(self):
    return self.a
  @staticmethod
  def getB():
    return 2
  @classmethod
  def getCN():
    return cls.__name__

if __name__ == '__main__':
  d = de()
  print 'd.getA() = %s' % d.getA()
  print 'de.getB() = %s' % de.getB()
  print 'classname of de = %s' % de.getCN()
  print 'de.getA() = %s' % de.getA()

Execute it.
$ ./t.py
de.getA() = 1
de.getB() = 2
classname of de = de
Traceback (most recent call last):
  File "./t.py", line 15, in
    print 'de.getA() = %s' % de.getA()
TypeError: unbound method getA() must be called with de instance as first argument (got nothing instead)



Wish this helps.
regards,
Stanley Huang

Comments

Popular posts from this blog

[Level 1] Rar tool for Solaris.

[Level 2] iif in Python