gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 07:11:56 25 4
gpt4 key购买 nike

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

(我知道这是非常不面向对象的,并且在编写良好的程序中可能永远不会有用,但我想知道语言是否提供它)

例如:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com