python-3.x - 我可以使实例方法不可调用为静态方法吗?

标签 python-3.x

我有一个名为opened()@asynccontextmanager 方法,它是File 类的一个实例方法。有时我会错误地使用一个类来调用它,例如 File.opened()。然后它会失败,因为对象未初始化(例如名称)并出现一个并未真正表达问题的错误。

AttributeError: 'str' object has no attribute 'opened'

有什么办法可以避免这种情况吗?

例子

class File: 
   def __init__(self, file_name):
        self.file_name = file_name

    @asynccontextmanager
    async def opened(self):
        open(self.file_name)
        # do other things

这应该没问题:

file = File('input.csv')
async with file.opened() as file_handle:
    #do stuff

但是他应该会产生一个错误,告诉我如果不先创建一个对象我就不能使用实例方法:

async with File.opened() as file_handle:
     # does not work, and should not be allowed

最佳答案

您可以检查 self 是否是 File 的实例,以便您可以使用更友好的错误消息引发异常:

@asynccontextmanager
async def opened(self):
    if not isinstance(self, File):
        raise RuntimeError('opened() must be called as a method bound to a File instance.')
    open(self.file_name)

关于python-3.x - 我可以使实例方法不可调用为静态方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53231884/

相关文章:

python - 使用 unittest 在 Python 中模拟类

python - 在哪里可以查看内置 Python 方法 id() (Python 3.x) 的代码?

python - 如何根据第一个输入显示/隐藏输入选项?

python-3.x - 使用influxdb-python的Influxdb批量插入

python - Pip 列表与 conda 列表显示不同的包版本

python - 启动和停止外部程序?

python - 检查是否可以使用另一个函数的参数调用函数

python-3.x - 无法在 M1 Mac 上使用 Pip 安装 OpenCV

python - 具有依赖项初始化错误 : ModuleNotFoundError or ImportError 的自定义包

python - pip 3 : bad interpreter: No such file or directory