如何从python中的@staticmethod函数中找出我所调用的类?

时间:2011-07-04 14:34:46

标签: python inheritance

当调用静态方法时,有没有办法让它知道从哪个子类调用它?

(我知道这是非常不合适的,在编写得很好的程序中可能永远不会有用,但我想知道该语言是否提供了它)

例如:

class A(object):
  @staticmethod
  def foo():
    print 'bar'
    # *** I would like to print either 'A' or 'B' here

class B(A):
  pass

A.foo()
B.foo()

1 个答案:

答案 0 :(得分:9)

您必须使用@classmethod代替@staticmethod。使用类方法,您将获得对作为第一个参数传入的类的引用:

class A(object):
  @classmethod
  def foo(cls):
    print cls.__name__
    # *** I would like to print either 'A' or 'B' here

class B(A):
  pass

A.foo()
B.foo()

输出:http://codepad.org/bW3E51r9

  

一个
  乙

相关问题