如何在 Python 中初始化一个空值对象?
How can I initialize an object with a null value in Python?
class FileCompoundDefinition(AbstractCompoundDefinition):
# <editor-fold desc="(type declaration)">
__include_dependency_graph: IncludeDepGraphTagFL
__inner_namespace: InnerNamespaceTag
__brief_description: BriefDescription
__detailed_description: DetailedDescription
__location: LocationDefinitionCL
# </editor-fold>
# <editor-fold desc="(constructor)">
def __init__(self,
id: str,
kind: str,
language: str,
compound_name: str):
super().__init__(id, kind, compound_name)
self.__language = language
self.__includes_list = []
self.__inner_class_list = []
self.__include_dependency_graph = None
self.__inner_namespace = None
self.__brief_description = None
self.__detailed_description = None
self.__location = None
# </editor-fold>
在上面的源代码中,以下几行显示错误:
self.__include_dependency_graph = None
self.__inner_namespace = None
self.__brief_description = None
self.__detailed_description = None
self.__location = None
如何使用 None
值初始化对象?
使用typing.Optional
以下不会引起任何警告。
from typing import Optional
class FileCompoundDefinition(AbstractCompoundDefinition):
__location: Optional[LocationDefinitionCL]
def __init__(...)
self.__location = None
...
self.__location = LocationDefinitionCL()
见
As a shorthand for Union[T1, None]
you can write Optional[T1]
; for example, the above is equivalent to:
from typing import Optional
def handle_employee(e: Optional[Employee]) -> None: ...
class FileCompoundDefinition(AbstractCompoundDefinition):
# <editor-fold desc="(type declaration)">
__include_dependency_graph: IncludeDepGraphTagFL
__inner_namespace: InnerNamespaceTag
__brief_description: BriefDescription
__detailed_description: DetailedDescription
__location: LocationDefinitionCL
# </editor-fold>
# <editor-fold desc="(constructor)">
def __init__(self,
id: str,
kind: str,
language: str,
compound_name: str):
super().__init__(id, kind, compound_name)
self.__language = language
self.__includes_list = []
self.__inner_class_list = []
self.__include_dependency_graph = None
self.__inner_namespace = None
self.__brief_description = None
self.__detailed_description = None
self.__location = None
# </editor-fold>
在上面的源代码中,以下几行显示错误:
self.__include_dependency_graph = None
self.__inner_namespace = None
self.__brief_description = None
self.__detailed_description = None
self.__location = None
如何使用 None
值初始化对象?
使用typing.Optional
以下不会引起任何警告。
from typing import Optional
class FileCompoundDefinition(AbstractCompoundDefinition):
__location: Optional[LocationDefinitionCL]
def __init__(...)
self.__location = None
...
self.__location = LocationDefinitionCL()
见
As a shorthand for
Union[T1, None]
you can writeOptional[T1]
; for example, the above is equivalent to:from typing import Optional def handle_employee(e: Optional[Employee]) -> None: ...