Control the Number of Printed Decimals with f-String
If you want to limit the number of decimals being printed, use the f-string as shown above.
Control the Number of Printed Decimals with f-String Read More »
If you want to limit the number of decimals being printed, use the f-string as shown above.
Control the Number of Printed Decimals with f-String Read More »
When using a Python list as an argument in a function, you might inadvertently change its value. For example, in the code above, using the append method ends up changing the values of the original list.
If you want to avoid this side effect, use copy with a list or deepcopy with a nested list in a function.
Avoid Side Effects When Using List in a Function Read More »
It is common to use the else statement to cover the cases that the if statement doesn’t cover. For example, in the code above, we use the else statement when the item is not on the price list.
This method works, but we query the dictionary twice and use two statements just to return almost the same thing. We can reduce the redundancy in the code with the get method.
get looks up a key and returns the default value when a key doesn’t exist.
It can be confusing for others to understand the roles of some values in your code. Thus, it is a good practice to assign names to your variables to make them readable to others.
Have you ever had multiple classes that have similar attributes and methods? If so, use inheritance to organize your classes.
Inheritance allows us to define a parent class and child classes. A child class inherits all the methods and attributes of the parent class.
In the code above, we define the parent class to be Dog and the child classes to be Dachshund and Poodle. With class inheritance, we avoid repeating the same piece of code multiple times.
With a data class, you don’t need an init method to assign values to its attributes. However, sometimes you might want to use an init method to initialize certain attributes.
That is when dataclass’s __post_init__ comes in handy.
In the code above, I use __post_init__ to initialize the attribute info using the attributes names and ages.
If your Python string gets very long, you can break it up using either parentheses or a backslash.
If you want to create new directories and files, you can either use os or pathlib. However, pathlib’s syntax is more straightforward and easier to understand than os’s syntax.
Normally, you need to implement the __eq__ method so that you can compare between two classes. dataclasses automatically implements the __eq__ method for you.
With dataclasses, you can compare between 2 classes by only specifying their attributes.
If you don’t want anybody to adjust the attributes of a class, use @dataclass(frozen=True).
In the example above, changing the attribute color of the DataClassDog‘s instance will throw an error.