static method vs class method in python

Tags:

http://www.python.org/download/releases/2.2.3/descrintro/#staticmethods

static method는 C++의 그것과 같습니다.

class Foo:
  @staticmethod
  def bar():
    print "I'm a static"
    
Foo.bar()

하지만, class method는 cls라는 인자를 받고 이 인자는 해당 메소드를 부른 클래스를 가리킵니다.

class Parent:
  @classmethod
  def baz(cls, param):
    print "Called by", cls, " and given ", param

class Child(Parent):
  pass

Child.baz(1) # Called by baz and given 1

그리고 python 사용자들은 static method보다는 class method를 선호하는 것 같습니다. 심지어 static variable도 없어서 hack을 쓰는듯… 또 그 static 변수란게 클래스의 경우에만 없는게 아니라 메소드에도 없습니다. 그래서.. 아래와 같이 하는게 하나의 방법?!

class Foo:
  @staticmethod
  def bar():
    if not "v" in dir(Foo.bar):
      Foo.bar.v = 0
    Foo.bar.v += 1
    print Foo.bar.v
    
Foo.bar()
Foo.bar()
Foo.bar()

이외에도 static variable의 부재 문제를 해결하는 방법이, decorator를 쓴다던가하는 다른 방법도 있나보지만 일단 해킹 없이 코딩하는게 낫겠죠..

Comments

2 responses to “static method vs class method in python”

  1. 이정민 Avatar
    이정민

    >>> class Foo:
    … static_variable = 0
    … def __init__(self):
    … Foo.static_variable += 1
    … print Foo.static_variable

    >>> Foo()
    1

    >>> Foo()
    2

    >>> Foo()
    3

    >>>

  2. mkseo Avatar
    mkseo

    감사합니다. 덕분에 많이 배웠습니다.

    Static Variable vs Class Variable in Python: http://tinyurl.com/36o2c2

Leave a Reply

Your email address will not be published. Required fields are marked *