从另一个类调用类方法

云雀

在Python中,有没有一种方法可以从另一个类中调用一个类方法?我正在尝试在Python中旋转自己的MVC框架,但无法弄清楚如何从另一个类中的一个类调用方法。

这是我想发生的事情:

class A:
    def method1(arg1, arg2):
        # do code here

class B:
    A.method1(1,2)

我正在从PHP慢慢进入Python,因此我正在寻找与PHP等效的Python call_user_func_array()

aaronasterling:

更新:刚刚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. classmethod装饰器应用于method1:您将不再能够引用其中selfmethod1在这种情况下,您将cls在该位置传递一个实例A
  3. 在应用staticmethod装饰器method1:您将不再能够引用self,或clsstaticmethod1但你可以硬编码到引用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中的模块级函数。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章