从另一个类调用类方法

新手上路,请多包涵

有没有办法从另一个类调用一个类的方法?我正在寻找类似 PHP 的 call_user_func_array() 的东西。这是我想要发生的事情:

 class A:
    def method1(arg1, arg2):
        ...

class B:
    A.method1(1, 2)

原文由 Lark 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 220
2 个回答

更新:刚刚在您的帖子中看到了对 call_user_func_array 的引用。那不一样。使用 getattr 获取函数对象,然后用你的参数调用它

class A(object):
    def method1(self, a, b, c):
        # foo

method = A.method1

method 现在是一个实际的函数对象。您可以直接调用(函数是 python 中的一流对象,就像在 PHP > 5.3 中一样)。但是下面的考虑仍然适用。也就是说,上面的例子会崩溃,除非你用下面讨论的两个装饰器之一装饰 A.method1 ,将 A 的实例作为第一个参数传递给它,或者访问方法 A 的实例。

 a = A()
method = a.method1
method(1, 2)


您可以通过三种方式执行此操作

  1. 使用 A 的实例调用 method1 (使用两种可能的形式)
  2. apply the classmethod decorator to method1 : you will no longer be able to reference self in method1 but you will get passed a cls 实例在它的位置 A 在这种情况下。
  3. apply the staticmethod decorator to method1 : you will no longer be able to reference self , or cls in staticmethod1 但您可以 A 的引用硬编码到其中,尽管很明显,这些引用将由 A 的所有子类继承,除非它们专门覆盖 method1 致电 super

一些例子:

 class Test1(object): # always inherit from object in 2.x. it's called new-style classes. look it up
    def method1(self, a, b):
        return a + b

    @staticmethod
    def method2(a, b):
        return a + b

    @classmethod
    def method3(cls, a, b):
        return cls.method2(a, b)

t = Test1()  # same as doing it in another class

Test1.method1(t, 1, 2) #form one of calling a method on an instance
t.method1(1, 2)        # form two (the common one) essentially reduces to form one

Test1.method2(1, 2)  #the static method can be called with just arguments
t.method2(1, 2)      # on an instance or the class

Test1.method3(1, 2)  # ditto for the class method. It will have access to the class
t.method3(1, 2)      # that it's called on (the subclass if called on a subclass)
                     # but will not have access to the instance it's called on
                     # (if it is called on an instance)

请注意,就像 self 变量的名称完全取决于您一样, cls 变量的名称也是如此,但这些是习惯值。

既然你知道怎么做了,我就认真考虑 要不要去做。通常,要调用未绑定(没有实例)的方法最好保留为 python 中的模块级函数。

原文由 aaronasterling 发布,翻译遵循 CC BY-SA 4.0 许可协议

只需调用它并提供 self

 class A:
    def method(self, x, y):
        print(x + y)

class B:
    def call_a(self):
        A.method(self, 1, 2)

b = B()
b.call_a()

输出:

 3

原文由 ratiotile 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏