如何调用class方法而不在命令行中写入类名

2024-04-26 11:54:17 发布

您现在位置:Python中文网/ 问答频道 /正文

下面是代码,只是一个简单的例子:

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)

代码可能错了,但我只想知道方法。有没有办法做到这一点?你知道吗


Tags: 模块方法run代码pyimportselfreturn
1条回答
网友
1楼 · 发布于 2024-04-26 11:54:17

如果在类中定义了方法,那么不创建对象或不引用类,就不可能调用该方法。你知道吗

至于随机示例randint是函数引用

_inst = Random()
randint = _inst.randint

创建Random对象,randint函数引用存储在randinthttps://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)

相关问题 更多 >