简体   繁体   English

在不传递实例变量或默认值的情况下初始化 python 数据类 object

[英]Initializing python dataclass object without passing instance variables or default values

I want to initialize python dataclass object even if no instance variables are passed into it and we have not added default values to the param我想初始化 python 数据类 object 即使没有实例变量传入它并且我们没有向参数添加默认值

@dataclass
class TestClass:
   
   paramA: str
   paramB: float
   paramC: str

obj1 = TestClass(paramA="something", paramB=12.3)

Here it won't allow me to create the object & it will throw在这里它不允许我创建 object 并且它会抛出

TypeError: __init__() missing 1 required positional argument: 'paramC'

I can use the default value to resolve this error.我可以使用默认值来解决这个错误。

paramC: str = None
# OR
paramC: str = ""

But I don't want to use a default value for paramC because I want a scenario such that if we pass paramC then only it should be there in the object else it should not be there.但是我不想为 paramC 使用默认值,因为我想要一个场景,如果我们通过 paramC,那么只有它应该存在于 object 中,否则它不应该存在。 So if we use default value here paramC will always be there in the object with value None OR empty string.因此,如果我们在这里使用默认值 paramC 将始终存在于 object 中,值为None或空字符串。

I would like to skip initialization of a param if it is not passed during initialization.如果在初始化期间未传递参数,我想跳过参数的初始化。

You can use Optional typing.您可以使用可选类型。

from typing import Optional

@dataclass
class TestClass:
   
   paramA: str
   paramB: float
   paramC: Optional[str] = None

obj1 = TestClass(paramA="something", paramB=12.3)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM