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

标签 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()

最佳答案

为此,您必须使用 @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

A
B

关于python - 如何从 python 中的 @staticmethod 函数中找出我被调用的类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6572856/

相关文章:

c++ - error C2504 循环包含

scala - 混入嵌套在对象中的特征时出现 AbstractMethodError - 仅在编译和导入时

inheritance - 如何在grails域子类中对继承的属性添加约束

c++ - 混合抽象类和模板,灾难的秘诀?

python - 是否可以在 Pytorch 中不填充的情况下对动态长度句子进行最大池化?

python - 如何用OpenCV将飞镖板从背景中分离出来?

python - 如何获取外键的相关名称?

python - 将特定行从 CSV 文件迭代复制到新文件

python - 绘制点之间的连接线问题

c - 通过展开继承是否违反严格的别名规则?