python - 通过字典调用类方法

标签 python class methods dictionary

我正在开发一个类,该类描述一个可以用多个“单元”表示的对象,我会说,为了让事情变得简单。假设我们正在讨论长度。 (这实际上是更复杂的事情。)我希望用户能够输入 1 和“英寸”,例如,并自动获取以英尺、米、弗隆为单位的成员变量,你也有。我希望用户能够输入我正在处理的任何单位,并获取所有其他单位中的成员变量。我的想法是做这样的事情:

class length:
  @classmethod
  def inch_to_foot(cls,inch):
  # etc.
  @classmethod
  def inch_to_meter(cls,inch):
  # etc.

我想你明白了。然后我会在类中定义一个字典:

  from_to={'inch':{'foot':inch_to_foot,'meter':inch_to_meter, ...},
           'furlong':{'foot':furlong_to_foot, ...},
           #etc
           }

那么我想我可以写一个 __init__ 方法

   def __init__(self,num,unit):
       cls = self.__class__
       setattr(self,unit,num)
       for k in cls.from_to[unit].keys:
           setattr(self,k,cls.from_to[unit][k](num)

但是不行。我收到错误“类方法不可调用”。我有什么想法可以让这项工作成功吗?有什么想法可以放弃整个事情并尝试不同的方法吗?谢谢。

最佳答案

如果将 from_to 变量移至 __init__ 并将其修改为如下内容:

cls.from_to={'inch':{'foot':cls.inch_to_foot,'meter':cls.inch_to_meter, }}

那么我认为它会如你所期望的那样工作。

不幸的是,我无法回答为什么,因为我自己没有太多使用类方法,但我认为这与绑定(bind)方法和非绑定(bind)方法有关。无论如何,如果您打印代码中存储在 to_from 中的函数与经过我修改的函数,您会发现它们是不同的(我的是绑定(bind)的,您的是类方法对象)

希望能有所帮助!

编辑:我想得更多了一点,我认为问题是因为您在将函数绑定(bind)到类之前存储了对函数的引用(毫不奇怪,绑定(bind)一旦类的其余部分被解析,就会发生)。我的建议是忘记存储函数引用的字典,而是存储(以您选择的某种表示形式)指示您可以在之间更改的单位的字符串。例如,您可以选择类似的格式,例如:

from_to = {'inch':['foot','meter']}

然后在__init__期间使用getattr查找函数 例如:

class length:    
    from_to = {'inch':['foot','meter']}

    def __init__(self,num,unit):
        if unit not in self.from_to:
            raise RuntimeError('unit %s not supported'%unit)

        cls = self.__class__
        setattr(self,unit,num)

        for k in cls.from_to[unit]:
            f = getattr(cls,'%s_to_%s'%(unit,k))
            setattr(self,k,f(num))            

    @classmethod
    def inch_to_foot(cls,inch):
        return inch/12.0

    @classmethod
    def inch_to_meter(cls,inch):
        return inch*2.54/100    

a = length(3,'inches')
print a.meter
print a.foot
print length.inch_to_foot(3)

关于python - 通过字典调用类方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20850504/

相关文章:

php - 如何在 Laravel 中添加类别名

python - SymPy 是否正确求解此 ODE?

返回正确维度数组的 Pythonic 方法

python - 有没有更好的方法来完成这个 python 练习? (初学者)

java - ProGuards 总是删除方法调用

java - 在抽象类中创建方法而不是在扩展它的类中重写它们是一个好习惯吗?

JAVA:对正确的 for 循环迭代感到困惑?

python - 值错误 : operands could not be broadcast together with shapes (224, 224) (180,180)

python - 从原始文件外部的类导入函数

ios - 从另一个类 Objective-C 调用时方法不起作用