【问题标题】:Is there any problem in calling a static method from type name in python?从python中的类型名称调用静态方法有什么问题吗?
【发布时间】:2020-12-07 09:12:13
【问题描述】:
我是否应该注意这样做可能引起的任何问题?
例子:
class A(object):
def __init__(self, a):
self.a = a
@staticmethod
def add1(a):
return a+1
x = A(1)
y = type(x).add1(2)
我的用例是调用一个静态方法来处理我们无法再使用的对象生成的数据。
【问题讨论】:
标签:
python-3.x
static-methods
【解决方案1】:
身份的简单测试给了我们:
x = A(1)
print(type(x) is A)
True
print(type(x).add is A.add)
True
因此,基于此应该没有任何问题,但我不是 100% 确定。虽然我可能会访问 x.__class__ 属性,在我看来这更直观。
编辑:来自关于 type 函数的 Python 文档:
使用一个参数,返回对象的类型。返回值是一个类型对象,一般与object.__class__返回的对象相同。