我在创建 Python 类时遇到了一些问题。我的任务是使用一些解析方法创建对象。但我想使用 __init__
比如我有
class A:
@classmethod
def create_from_file(cls, file):
# Create instance form file...
return self
这让我有机会使用这样的命令创建对象
a = A.create_from_file()
但是这段代码让我有机会使用 __init__
a = A() 不会引发异常...
当我尝试添加自己的 __init__ 方法时,我的解析函数也引发异常。
class A:
def __init__(self):
raise NotImplementedError
@classmethod
def create_from_file(cls, file):
# Create instance form file...
return self
我该如何解决这个问题,编写此类的最 Pythonic 方式是什么?
请您参考如下方法:
__init__不负责创建实例。这是一个钩子(Hook)方法,Python 会在实例创建之后为您调用。您不能阻止从那里创建实例。此外,您不想阻止所有 实例的创建,甚至是您的classmethod必须在某个时候创建一个实例。
由于您要做的只是在您的工厂方法未用于创建实例时引发异常,因此在 __init__ 中引发异常仍然没问题。方法。这将防止新实例被分配到任何地方。然后您需要做的是区分直接访问和正在使用的工厂方法。
您可以通过几种不同的方式实现这一点。您可以使用只有工厂方法传入的“ secret ” token :
_token = object() # unique token to flag factory use
class A:
def __init__(self, data, _from_factory=None):
if _from_factory is not _token:
raise TypeError(f"Can't create {type(self).__name__!r} objects directly")
self._data = data
@classmethod
def create_from_file(cls, file):
data = file.read()
return cls(data, _from_factory=_token)
classmethod仍然创建一个实例,__init__仍然会为该实例调用,并且不会引发异常,因为传入了正确的 token 。
你可以让你的类成为模块的实现细节,并且只提供一个公共(public)工厂函数:
def create_from_file(cls, file):
data = file.read()
return _A(data)
class _A:
def __init__(self, data):
self._data = data
现在公共(public) API 只给你 create_from_file() ,前导下划线告诉开发人员 _A()是内部名称,不应在模块外部依赖。
实际创建实例是 object.__new__ method 的责任;您还可以使用该方法来防止创建新实例。您可以使用我上面显示的相同标记方法,或者您可以使用 super() 完全绕过它调用原始的覆盖实现:
class A:
def __new__(cls, *args, **kwargs):
raise TypeError(f"Can't create {cls.__name__!r} objects directly")
def __init__(self, data):
self._data = data
@classmethod
def create_from_file(cls, file):
data = file.read()
# Don't use __new__ *on this class*, but on the next one in the
# MRO. We'll have to manually apply __init__ now.
instance = super().__new__(cls)
instance.__init__(data)
return instance
这里直接调用A()将引发异常,但通过使用 super().__new__在classmethod我们绕过了 A.__new__实现。
备注:__new__隐含地成为一个staticmethod , 所以我们必须手动传入 cls当我们从 classmethod 中调用它时的参数.
