简体   繁体   中英

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

@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

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. So if we use default value here paramC will always be there in the object with value None OR empty string.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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