Python 从另一个类调用类方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3856413/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 13:05:12  来源:igfitidea点击:

Call Class Method From Another Class

python

提问by Lark

In Python, is there a way to call a class method from another class? I am attempting to spin my own MVC framework in Python and I can not figure out how to invoke a method from one class in another class.

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

Here is what I want to happen:

这是我想要发生的事情:

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

class B:
    A.method1(1,2)

I am slowly getting into Python from PHP so I am looking for the Python equivalent of PHP's call_user_func_array().

我正在慢慢地从 PHP 进入 Python,所以我正在寻找与 PHP 的call_user_func_array().

采纳答案by aaronasterling

update: Just saw the reference to call_user_func_arrayin your post. that's different. use getattrto get the function object and then call it with your arguments

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

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

method = A.method1

methodis now an actual function object. that you can call directly (functions are first class objects in python just like in PHP > 5.3) . But the considerations from below still apply. That is, the above example will blow up unless you decorate A.method1with one of the two decorators discussed below, pass it an instance of Aas the first argument or access the method on an instance of A.

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

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


You have three options for doing this

您有三种选择来执行此操作

  1. Use an instance of Ato call method1(using two possible forms)
  2. apply the classmethoddecorator to method1: you will no longer be able to reference selfin method1but you will get passed a clsinstance in it's place which is Ain this case.
  3. apply the staticmethoddecorator to method1: you will no longer be able to reference self, or clsin staticmethod1but you can hardcode references to Ainto it, though obviously, these references will be inherited by all subclasses of Aunless they specifically override method1and do not call super.
  1. 使用实例A调用method1(使用两种可能的形式)
  2. classmethod装饰器应用于method1:您将无法再引用selfin,method1但您将cls在它的位置传递一个实例,A在这种情况下。
  3. 在应用staticmethod装饰器method1:您将不再能够引用self,或clsstaticmethod1但你可以硬编码到引用A到它,但很明显,这些文献将被所有子类继承A,除非他们专门覆盖method1,不叫super

Some examples:

一些例子:

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)

Note that in the same way that the name of the selfvariable is entirely up to you, so is the name of the clsvariable but those are the customary values.

请注意,self变量的名称完全取决于您,cls变量的名称也是如此,但这些都是惯用的值。

Now that you know how to do it, I would seriously think about ifyou want to do it. Often times, methods that are meant to be called unbound (without an instance) are better left as module level functions in python.

现在,你知道怎么做了,我会认真思考一下,如果你想这样做。很多时候,打算被称为未绑定(没有实例)的方法最好保留为 Python 中的模块级函数。

回答by ratiotile

Just call it and supply self

只需调用它并提供 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()

output: 3

输出:3

回答by Joshua Hufford

You can call a function from within a class with:

您可以使用以下命令从类中调用函数:

A().method1()

A().method1()

回答by Xrhstos Mpaoui

class CurrentValue:

    def __init__(self, value):
        self.value = value

    def set_val(self, k):
        self.value = k

    def get_val(self):
        return self.value


class AddValue:

    def av(self, ocv):
        print('Before:', ocv.get_val())
        num = int(input('Enter number to add : '))
        nnum = num + ocv.get_val()
        ocv.set_val(nnum)
        print('After add :', ocv.get_val())


cvo = CurrentValue(5)

avo = AddValue()

avo.av(cvo)

We define 2 classes, CurrentValue and AddValue We define 3 methods in the first class One initin order to give to the instance variable self.value an initial value A set_val method where we set the self.value to a k A get_val method where we get the valuue of self.value We define one method in the second class A av method where we pass as parameter(ovc) an object of the first class We create an instance (cvo) of the first class We create an instance (avo) of the second class We call the method avo.av(cvo) of the second class and pass as an argument the object we have already created from the first class. So by this way I would like to show how it is possible to call a method of a class from another class.

我们定义了 2 个类,CurrentValue 和 AddValue 我们在第一个类中定义了 3 个方法一个init为了给实例变量 self.value 一个初始值一个 set_val 方法,我们将 self.value 设置为 ak 一个 get_val 方法,我们得到self.value 的值 我们在第二个类中定义一个方法 av 方法,我们将第一个类的对象作为参数(ovc)传递 我们创建第一个类的实例(cvo) 我们创建一个实例(avo)第二个类我们调用第二个类的 avo.av(cvo) 方法并将我们已经从第一个类创建的对象作为参数传递。所以通过这种方式,我想展示如何从另一个类调用一个类的方法。

I am sorry for any inconvenience. This will not happen again.

对于任何不便,我深表歉意。这不会再发生了。

Before: 5

之前:5

Enter number to add : 14

输入要添加的数字:14

After add : 19

添加后:19