用不同的类调用类方法

时间:2017-01-20 14:13:44

标签: python python-3.x

假设我们有以下两个类:

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' method()obj2self

>>> Class1.method(o2)
Class1.method() with self = <__main__.Class2 object at 0x...>

现在的问题是:如何使用类方法做类似的事情?

>>> Class1.clsmethod(Class2)
Class1.clsmethod() with cls = <__main__.Class2 object at 0x...>

Class1必须替换什么?使用type(Class1)(&#34;类Class1&#34;类似于&#34;类obj1)的直观方法不起作用,因为类方法是不是元类的属性。

1 个答案:

答案 0 :(得分:2)

通过访问__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 = <class '__main__.Class2'>

Class2.clsmethod.__func__(Class1)  # <----
# prints
# Class2.clsmethod() with cls = <class '__main__.Class1'>