首页 > 解决方案 > 如何在不在命令行中写入类名的情况下调用类方法

问题描述

这是代码,它只是一个简单的例子:

class func(object):

    def cacul(self, a, b):
        return a+b

    def run_cacul(self, a, b):
        return self.cacul(a, b)

我正在尝试run_cacul()通过在命令行中导入此模块来调用类方法。模块名称是“foo.py”

import foo

foo.func().run_cacul(2,3)

它太长了!!我不想写类名,就像python的系统模块一样random.py,它省略了类名Random()

import random

random.randint(12,23)

代码可能是错误的,但我只想知道方法。有什么办法可以做到这一点?

标签: python

解决方案


如果您在类中定义了方法,那么在没有创建对象或没有引用该类的情况下,就不可能调用该方法。

至于随机示例randint是函数参考

_inst = Random()
randint = _inst.randint

创建 Random 的对象,并将randint函数引用存储在randint. https://github.com/python/cpython/blob/master/Lib/random.py#L775 对客户端(我们)隐藏对象创建。

沿着类似的路线,你可以做同样的事情:foo.py

class func(object):

    def cacul(self, a, b):
        return a+b

    def run_cacul(self, a, b):
        return self.cacul(a, b)

obj = func()
run_cacul = obj.run_cacul

那么你可以这样做

from foo import ran_cacul
ran_cacul(4,5)

推荐阅读