我们假设我们有以下两个类:
class Class1:
def method(self):
print("Class1.method() with self =", self)
@classmethod
def clsmethod(cls):
print("Class1.clsmethod() with cls =", cls)
obj1 = Class1()
class Class2:
def method(self):
print("Class2.method() with self =", self)
@classmethod
def clsmethod(cls):
print("Class2.clsmethod() with cls =", cls)
obj2 = Class2()
对于正常的绑定方法,很容易注入不同的自我.我们只需调用Class1的方法(),但使用obj2作为self:
>>> Class1.method(o2)
Class1.method() with self = <__main__.class2 object at>
现在的问题是:我怎么能用类方法做类似的事情呢?
>>> Class1.clsmethod(Class2)
Class1.clsmethod() with cls = <__main__.class2 object at>
什么样的Class1必须被替换?使用类型(Class1)(“类1”类似于“obj1类”)的直观方法不起作用,因为类方法不是元类的属性.
最佳答案 通过访问__func__属性,您可以获得未绑定的函数对象.
class Class1:
def method(self):
print("Class1.method() with self =", self)
@classmethod
def clsmethod(cls):
print("Class1.clsmethod() with cls =", cls)
class Class2:
def method(self):
print("Class2.method() with self =", self)
@classmethod
def clsmethod(cls):
print("Class2.clsmethod() with cls =", cls)
Class1.clsmethod.__func__(Class2) #
# prints
# Class1.clsmethod() with cls =
Class2.clsmethod.__func__(Class1) #
# prints
# Class2.clsmethod() with cls =