我有一个名为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/