【问题标题】:How to use a variable in place of a method when calling a class?调用类时如何使用变量代替方法?
【发布时间】:2021-02-12 23:00:33
【问题描述】:

假设我在main.py 中有一个函数func,在mod.py 中有一个类TreeTree 具有方法 apple()orange()banana()。这是main.py

from . import mod

def func(arg, meth):
    tree = mod.Tree
    tree.meth(arg)

func 应该meth 参数调用来自Tree 的方法,而是尝试找到meth 属性。与其尝试查找属性,不如将其替换为变量?

【问题讨论】:

  • 你能说明你打算如何调用这个函数吗?你到底传递了什么meth
  • 方法之一; apple()orange()banana()
  • 你能分享Tree类吗?方法是classmethods 吗?您可能可以使用getattr 获得该方法:getattr(tree, meth)(arg)
  • 您不应该实例化Tree 实例(即tree = mod.Tree())吗?或者您是否尝试从Tree 访问静态方法/类方法?另外,meth 是什么数据类型?
  • @jfaccioni 是否实例化它并不重要,因为您只是在调用该方法,在这种情况下,这有点违背了类的目的,现在我想到了,我可能已经完成了from mod import *...

标签: python class variables methods


【解决方案1】:

您正在寻找getattr()

def func(arg, meth):
    tree = mod.Tree
    getattr(tree, meth)(arg)

这将访问由指定变量 (meth) 命名的对象 (tree) 的属性(属性或函数)。然后你就有了这个函数,你可以调用它了。

【讨论】:

  • 啊,好吧,我对那个方法感到困惑,因为我认为它只是为变量分配了一个属性。 = 已经可以做到这一点,所以我想如果它确实做到了,那么拥有它是没有意义的。
  • @Shidouuu 如果你想动态设置属性setattr()
猜你喜欢
  • 1970-01-01
  • 2023-03-05
  • 2023-03-19
  • 2020-10-18
  • 2021-06-08
  • 2012-05-05
  • 1970-01-01
  • 2011-04-20
  • 1970-01-01
相关资源
最近更新 更多