我想通过类上下文管理器强制对象实例化。因此,使其无法直接实例化。
我实现了此解决方案,但从技术上讲,用户仍然可以实例化对象。
class HessioFile:
"""
Represents a pyhessio file instance
"""
def __init__(self, filename=None, from_context_manager=False):
if not from_context_manager:
raise HessioError('HessioFile can be only use with context manager')
Run Code Online (Sandbox Code Playgroud)
和上下文管理器:
@contextmanager
def open(filename):
"""
...
"""
hessfile = HessioFile(filename, from_context_manager=True)
Run Code Online (Sandbox Code Playgroud)
有更好的解决方案吗?