Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/304.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何调用存储在变量中的方法?_Python_Class_Methods - Fatal编程技术网

Python 如何调用存储在变量中的方法?

Python 如何调用存储在变量中的方法?,python,class,methods,Python,Class,Methods,如果我有一个带有方法method1的类Foo,有没有办法在实例化之前将该方法存储在变量中,然后在该类实例化之后调用该变量 例如: class Foo: def method1(self, arg): print(self, arg) # something like this variable, but which can be called with instantiated class func = Foo.method1 foo = Foo() foo.fun

如果我有一个带有方法
method1
的类
Foo
,有没有办法在实例化之前将该方法存储在变量中,然后在该类实例化之后调用该变量

例如:

class Foo:
    def method1(self, arg):
        print(self, arg)

# something like this variable, but which can be called with instantiated class 
func = Foo.method1

foo = Foo()
foo.func(1)  # I want to call it in a similar way to this

在python中,函数和方法之间没有真正的区别——方法只是在类中定义的函数

对于我们来说,这意味着可以像调用任何其他函数一样调用存储在变量
func
中的函数。如果
func
指的是
Foo.method1
,则该函数有两个参数:
self
arg
。为了调用
func
,我们只需传递一个
Foo
实例作为
self
参数,另一个值作为
arg
参数:

func(foo, 1)

我们通常不必为
self
传递参数的原因是,通过实例访问方法会自动将函数
method1
转换为绑定方法,其中
self
参数是隐式传递的:

>>> Foo.method1  # Foo.method1 is a function
<function Foo.method1 at 0x7f9b3c7cf0d0>
>>>
>>> foo.method1  # but foo.method1 is a bound method!
<bound method Foo.method1 of <__main__.Foo object at 0x7f9b3c7dd9e8>>
>>Foo.method1#Foo.method1是一个函数
>>>
>>>foo.method1#但是foo.method1是一个绑定方法!
有关函数和方法的更多详细信息,请参见。

除了极好的答案之外,如果您访问的是静态或类属性,则可能不需要实例化该类:

class Container:
    class_var = "class_var"
    def __init__(self, inst_var):
        self.inst_var = inst_var
        print("Instantiated")

    @staticmethod
    def static_mtd(static_arg):
        print(static_arg)

    def instance_mtd(self):
        print(self.inst_var)

    @classmethod
    def class_mtd(cls):
        print(cls.class_var)

stat = Container.static_mtd
stat("static_arg")  # static_arg

inst = Container.instance_mtd
inst(Container("inst_var"))   # Instantiated, inst_var

inst2 = Container("inst_var2").instance_mtd   # Instantiated
inst2()  # inst_var2

clas = Container.class_mtd
clas()  # class_var

var = Container.class_var # class_var

因此,您可以将变量名
inst
分配给一个实例方法
容器。首先,instance_mtd
,稍后实例化
,并将实例化的
作为
self
参数反馈回
inst
。这当然是相当乏味的,这意味着重新分配的实例方法是在类之外有效地定义的。

哦,我从未意识到,对于未实例化的类,方法的行为是这样的。这回答了我的问题。我计划在将来把这个问题作为一个重复的目标,所以我稍微修改了一下,使它更简短,更切题。