Python 输入 class 实例属性作为输入参数的副本
Python typing of class instance attributes as copies of input args
当使用输入 Python 是否足够时:
class Something:
def __init__(self, arg1: str, arg2: Union[str, int]):
self.arg1 = arg1
self.arg2 = arg2
或者所有的东西都应该打字?以下是否有优点并且是编码约定?
class Something:
def __init__(self, arg1: str, arg2: Union[str, int]):
self.arg1: str = arg1
self.arg2: Union[str, int] = arg2
这取决于您的类型检查器的智能程度,但我希望所有当前的 Python 检查器都能够从第一种形式推断出 arg1
和 [= 的类型14=].
请注意,您 缺少 return 类型注释,-> None
:
class Something:
def __init__(self, arg1: str, arg2: Union[str, int]) -> None:
self.arg1 = arg1
self.arg2 = arg2
例如,参见 mypy documentation on Class basics:
The mypy type checker detects if you are trying to access a missing attribute, which is a very common programming error. For this to work correctly, instance and class attributes must be defined or initialized within the class. Mypy infers the types of attributes:
class A:
def __init__(self, x: int) -> None:
self.x = x # Aha, attribute 'x' of type 'int'
a = A(1)
a.x = 2 # OK!
a.y = 3 # Error: 'A' has no attribute 'y'
(大胆强调我的)。
否则,我更喜欢将实例属性注释放在 class 级别,这样它们更容易被其他开发人员阅读:
class Something:
arg1: str
arg2: Union[str, int]
def __init__(self, arg1: str, arg2: Union[str, int]) -> None:
self.arg1 = arg1
self.arg2 = arg2
在这里,这会导致您不得不重复自己,但您可以考虑 using the dataclasses
module 避免这种情况。
当使用输入 Python 是否足够时:
class Something:
def __init__(self, arg1: str, arg2: Union[str, int]):
self.arg1 = arg1
self.arg2 = arg2
或者所有的东西都应该打字?以下是否有优点并且是编码约定?
class Something:
def __init__(self, arg1: str, arg2: Union[str, int]):
self.arg1: str = arg1
self.arg2: Union[str, int] = arg2
这取决于您的类型检查器的智能程度,但我希望所有当前的 Python 检查器都能够从第一种形式推断出 arg1
和 [= 的类型14=].
请注意,您 缺少 return 类型注释,-> None
:
class Something:
def __init__(self, arg1: str, arg2: Union[str, int]) -> None:
self.arg1 = arg1
self.arg2 = arg2
例如,参见 mypy documentation on Class basics:
The mypy type checker detects if you are trying to access a missing attribute, which is a very common programming error. For this to work correctly, instance and class attributes must be defined or initialized within the class. Mypy infers the types of attributes:
class A: def __init__(self, x: int) -> None: self.x = x # Aha, attribute 'x' of type 'int' a = A(1) a.x = 2 # OK! a.y = 3 # Error: 'A' has no attribute 'y'
(大胆强调我的)。
否则,我更喜欢将实例属性注释放在 class 级别,这样它们更容易被其他开发人员阅读:
class Something:
arg1: str
arg2: Union[str, int]
def __init__(self, arg1: str, arg2: Union[str, int]) -> None:
self.arg1 = arg1
self.arg2 = arg2
在这里,这会导致您不得不重复自己,但您可以考虑 using the dataclasses
module 避免这种情况。