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)
代码可能是错误的,但我只想知道方法。有什么办法可以做到这一点?
解决方案
如果您在类中定义了方法,那么在没有创建对象或没有引用该类的情况下,就不可能调用该方法。
至于随机示例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)
推荐阅读
- html - 浏览器正在覆盖我的代码中的所有元素并将它们转换为链接
- python-2.7 - 读取、处理和显示 .EXR 格式图像中的像素
- google-sheets - 无法将值数组更新为 Google 工作表中的单个范围
- postman - 如何读取并保存我们在 Postman 中获取的 JSON 格式结果?
- javascript - 使用 Leetcode 973 的快速选择算法的错误
- django - 我在呈现内置密码重置确认表单中的字段时遇到问题
- elasticsearch - kibana 中的 elasticsearch 监控被破坏
- c# - 在 AngleSharp 中,如何使用字符串创建 DOM 元素?
- node.js - 无法让记录器 (winston) 创建日志文件
- python - 字符串在“eval”语句中被视为变量