Skip to content

Commit dca8295

Browse files
authored
Merge pull request labex-labs#36 from Sonatrix/master
Add default value & typing hint dataclasses
2 parents ca6a22d + ffeb795 commit dca8295

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

blog_files/pysheet.md

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3988,6 +3988,40 @@ with dataclass
39883988
>>> obj.val
39893989
2
39903990
```
3991+
### Default values
3992+
3993+
It is easy to add default values to the fields of your data class.
3994+
3995+
```python
3996+
>>> @dataclass
3997+
... class Product:
3998+
... name: str
3999+
... count: int = 0
4000+
... price: float = 0.0
4001+
...
4002+
>>> obj = Product("Python")
4003+
>>> obj.name
4004+
Python
4005+
>>> obj.count
4006+
0
4007+
>>> obj.price
4008+
0.0
4009+
```
4010+
4011+
### Type hints
4012+
4013+
It is mandatory to define the data type in dataclass. However, If you don't want specify the datatype then, use ```typing.Any```.
4014+
4015+
```python
4016+
>>> from dataclasses import dataclass
4017+
>>> from typing import Any
4018+
4019+
>>> @dataclass
4020+
... class WithoutExplicitTypes:
4021+
... name: Any
4022+
... value: Any = 42
4023+
...
4024+
```
39914025

39924026
## Virtual Environment
39934027

0 commit comments

Comments
 (0)