从另一个类调用类方法

问题描述:

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

以下是我想发生:

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

class B: 
    A.method1(1,2) 

我慢慢进入Python从PHP所以我找了Python相当于PHP的call_user_func_array()的。

+0

这是否真的需要一个类的方法,而不是一个功能?其他语言的静态方法不一定映射到Python中的类方法。给这个读:http://dirtsimple.org/2004/12/python-is-not-java.html – 2010-10-04 15:09:32

+5

@Ivo老实说,如果他在学习基础之前编写自己的MVC,你会关心什么?让他尝试并学习过程中的基础知识。退出对提问人员的尊重。 – aaronasterling 2010-10-04 15:38:47

+4

@AaronMcSmooth这是诚实的建议 - 他目前的问题甚至没有一个明智的答案,因为它没有任何意义,这是经常发生的事情。我试图写一个答案,但我只能建议先学习python基础知识。我会在下次添加一些“很好的”;) – 2010-10-04 15:47:27

更新:刚刚在您的帖子中看到了对call_user_func_array的引用。那不一样。使用getattr得到函数对象,然后用你的论点

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

methodname = 'method1' 
method = getattr(A, methodname) 

method把它现在是一个实际的函数对象。你可以直接调用(函数是python中的第一类对象,就像在PHP> 5.3中一样)。但是从下面的考虑仍然适用。也就是说,除非您用下面讨论的两个修饰器之一修饰A.method1,否则将上述示例炸掉,将A作为第一个参数的实例或将getattr应用于A的实例。

a = A() 
method = getattr(a, methodname) 
method(1, 2) 

你有这样做的

  1. 使用的A实例method1(使用两种可能的形式)来调用
  2. classmethod装饰适用于method1三个选项:你会不会更长的时候可以参考selfmethod1,但是您会在的地方通过cls实例在这种情况下为。
  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变量的名称,但这些是常用的值。

既然你知道如何去做,我会认真考虑如果你想要做。通常情况下,被称为unbound(没有实例)的方法最好作为python中的模块级函数。

+0

'@classmethod 中cls的含义def method3(cls,a,b): return cls.method2(a,b)' – 2018-02-06 04:39:32

只是把它和供应self

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

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

b = B() 
b.call_a() 

输出:3

+0

这个例子是错误的,因为您正在将B类引用传递给A类方法 – 2017-11-21 16:59:21

+0

I只要所有在方法中被称为self.x的属性都存在于B @ – a1an 2018-03-06 15:46:40

+0

@VarunMaurya中,Python就会使用鸭子打字,所以不会检查类。正如a1an所说,只要你提供了一个具有正确属性的对象,就可以工作。 – ratiotile 2018-03-07 22:50:46